﻿//==========T_DICT.cpp==========
module T_DICT;

import <iostream>;
import <vector>;
import <string>;
import <any>;
import <unordered_map>;
import <set>;
import <map>;
import <set>;
import <stdexcept>;
import <chrono>;
import <iomanip>;
import <sstream>;
import <shared_mutex>;
import <mutex>;
import <atomic>;
import <thread>;
import <functional>;
import <format>;

namespace DICT {
	//==========公共方法定义==========
	//=====构造与初始化=====
	Dict::Dict(std::string su_name,
		std::string dict_name,
		std::string root_node_key,          //仅在把本dict整体插入另一个dict时使用
		int total_max_listen_num,           //最大监听数量(与以下三个参数无关，当到达最大数量时，新注册的监听会被拒绝)
		int su_max_listen_num,              //su最大监听数量
		int hu_max_listen_num,              //hu最大监听数量
		int vu_max_listen_num,              //vu最大监听数量std::vector<std::string>
		bool turn_on_log,                   //开启日志ROM存储（开启同时开启自动清理防止内存溢出）
		bool turn_on_error_log,             //开启错误日志记录到日志流
		bool turn_on_print_log,             //开启日志打印到控制台
		bool turn_on_auto_save_log,         //自动保存日志到文件
		std::string log_save_path,          //日志保存路径（开启日志保存却不设置保存路径时无法开启日志报错，并报错）
		bool turn_on_auto_clean_recycle,    //是否开启回收站功能，自动回收弃用节点，当不需要时可以关闭（比如静态大小数据库运算时）
		bool turn_on_operation_counter      //是否开启操作计数功能
	) : root_node_(std::make_shared<Node>()) {
		//字符串参数检查
		check_string_valid__(OPT::Dict, su_name);
		check_string_valid__(OPT::Dict, dict_name);
		check_string_valid__(OPT::Dict, root_node_key);
		if (is_init_) {
			throw_dict_error(su_name, su_name, OPT::Dict, {},
				error_.invalid_operation_error,"Dict has been initialized.");
		}
		else {
			//1. 操作锁
			DICT_LOCK.store(true);

			// 创建操作计数器 - 节点操作
			operation_counter oc(
				this,
				oc_type::global_operation_counter,
				nullptr
			);

			//元信息初始化

			//字典名称设置
			{
				//智能锁
				std::unique_lock lock(dict_name_.smtx);

				dict_name_.su_thread_id = std::this_thread::get_id();

				dict_name_.dict_name = dict_name;

				std::string op_time = get_time_string();
				log_op(
					op_time,
					su_name,
					su_name,
					OPT::Dict,
					{},
					"Dict name set to " + dict_name + "."
				);
			}
			//全局用户信息设置
			{
				//智能锁
				std::unique_lock lock(users_info_tree_.smtx);
				users_info_tree_.UFT.user_father_name = su_name;
				users_info_tree_.UFT.user_name = su_name;
				users_info_tree_.UFT.listen_num = 0;
				users_info_tree_.UFT.user_type = UserType::su;
				users_info_tree_.UFT.permission = Permission::rw;
				users_info_tree_.UFT.user_path_permission_list = {};

				std::string op_time = get_time_string();
				log_op(
					op_time,
					su_name,
					su_name,
					OPT::Dict,
					{},
					"Global user info set successfully."
				);
			}
			//根节点设置
			{
				//智能锁
				std::string creat_root_node_time = get_time_string();
				std::unique_lock lock(root_node_->info.smtx);
				root_node_->info.is_dict = true;
				root_node_->info.key = root_node_key;
				root_node_->info.create_time = creat_root_node_time;

				//给根节点上锁便于数据初始化
				//root_node_->is_locked.store(true, std::memory_order_release);

				std::string op_time = get_time_string();
				log_op(
					op_time,
					su_name,
					su_name,
					OPT::Dict,
					{},
					"Dict root node set successfully and locked."
				);
			}
			//监听设置
			{
				//智能锁
				std::unique_lock lock(user_listen_quota_.smtx);
				user_listen_quota_.max_listen_num = total_max_listen_num;
				user_listen_quota_.su_max_listen_num = su_max_listen_num;
				user_listen_quota_.hu_max_listen_num = hu_max_listen_num;
				user_listen_quota_.vu_max_listen_num = vu_max_listen_num;

				std::string op_time = get_time_string();
				log_op(
					op_time,
					su_name,
					su_name,
					OPT::Dict,
					{},
					"Listen limit number info set successfully."
				);
			}
			//日志设置
			{
				if (turn_on_log) {
					turn_on_log_.store(true);
					run_auto_clean_log__();
					turn_on_error_log_.store(turn_on_error_log);
					auto_save_log_.store(turn_on_auto_save_log);
					log_folder_path_ = log_save_path;
					print_log_ = turn_on_print_log;

					std::string op_time = get_time_string();
					log_op(
						op_time,
						su_name,
						su_name,
						OPT::Dict,
						{},
						"Log function set successfully."
					);
				}
			}
			// 回收站设置
			{
				if (turn_on_auto_clean_recycle) {
					run_recycle__();
					std::string op_time = get_time_string();
					log_op(
						op_time,
						su_name,
						su_name,
						OPT::Dict,
						{},
						"Auto recycle clean function set successfully."
					);
				}
			}
			//操作计数器设置
			{
				if (turn_on_operation_counter) {
					is_operation_counter_on_.store(true, std::memory_order_release);
					std::string op_time = get_time_string();
					log_op(
						op_time,
						su_name,
						su_name,
						OPT::Dict,
						{},
						"Operation counter function set successfully."
					);
				}
			}
			//日志
			//初始化完成时间
			std::string init_time = get_time_string();
			log_op(
				init_time,
				su_name,
				su_name,
				OPT::Dict,
				{},
				"Dict initialized successfully."
			);
			
			is_init_.store(true, std::memory_order_release);
			//不主动解锁,便于数据初始化
		}
	};
	//=====回收站=====
	void Dict::turn_on_auto_clean_recycle(std::string su) {
		//初始化校验
		init_check();
		//参数校验
		check_string_valid__(OPT::turn_on_auto_clean_recycle, su);
		UserCheckResult ucr = check_global_users_value__(OPT::turn_on_auto_clean_recycle, su, su);
		if (ucr.found_su) {
			check_su_thread_id__();
			if (auto_clean_recycle_is_running_.load(std::memory_order_acquire)) {
				throw_dict_error(su, su, OPT::turn_on_auto_clean_recycle, {},
					error_.invalid_operation_error, "Auto recycle clean is already running.");
			}
			else {
				run_recycle__();
			}
		}
		else {
			throw_dict_error(su, su, OPT::turn_on_auto_clean_recycle, {},
				error_.invalid_operation_error, "No permission to turn on auto recycle clean.");
		}
	};
	void Dict::turn_off_auto_clean_recycle(std::string su) {
		//初始化校验
		init_check();
		//参数校验
		check_string_valid__(OPT::turn_off_auto_clean_recycle, su);
		UserCheckResult ucr = check_global_users_value__(OPT::turn_off_auto_clean_recycle, su, su);
		if (ucr.found_su) {
			check_su_thread_id__();
			if (auto_clean_recycle_is_running_.load(std::memory_order_acquire)) {
				stop_recycle__();
			}
			else {
				throw_dict_error(su, su, OPT::turn_off_auto_clean_recycle, {},
					error_.invalid_operation_error, "Auto recycle clean is not running.");
			}
		}
		else {
			throw_dict_error(su, su, OPT::turn_off_auto_clean_recycle, {},
				error_.invalid_operation_error, "No permission to turn off auto recycle clean.");
		}
	};
	void Dict::clean_recycle(std::string su) {
		//初始化校验
		init_check();
		//参数校验
		check_string_valid__(OPT::clean_recycle, su);
		UserCheckResult ucr = check_global_users_value__(OPT::clean_recycle, su, su);
		if (ucr.found_su) {
			check_su_thread_id__();
			clean_recycle__();
		}
		else {
			throw_dict_error(su, su, OPT::clean_recycle, {},
				error_.invalid_operation_error, "No permission to clean recycle.");
		}
	};
	std::vector<std::vector<std::string>> Dict::get_recycled_items(
		std::string user_father,
		std::string user
	) {
		//初始化校验
		init_check();
		//参数校验
		check_string_valid__(OPT::get_recycled_items, user_father);
		check_string_valid__(OPT::get_recycled_items, user);

		UserCheckResult ucr = check_global_users_value__(OPT::get_recycled_items, user_father, user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		if (ucr.found_su) {
			check_su_thread_id__();
			return get_recycled_items__(user_father, user);
		}
		//字典锁
		else if (DICT_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::get_recycled_items, {},
				error_.invalid_operation_error, "No permission to get recycled items.Dict is locked.");
		}
		else {
			if (//su ,hu 需要hu有r_权限
				((ucr.found_su_and_hu) and (static_cast<int>(ucr.hu_global_permission) > 0))
				//hu,vu 需要hu至少有r_权限，vu有r_权限
				or (ucr.found_hu_and_vu and ((static_cast<int>(ucr.hu_global_permission) > 0) and (ucr.vu_global_permission == Permission::r_)))
				) {
				return get_recycled_items__(user_father, user);
			}
			else {
				throw_dict_error(user_father, user, OPT::get_recycled_items, {},
					error_.invalid_operation_error, "No permission to get recycled items.");
			}
		}
	};
	void Dict::restore_recycled_item(
		std::string user_father,
		std::string user,
		std::vector<std::string> recycle_item_path,//被回收的节点路径
		std::vector<std::string> restore_path,//为空时尝试恢复到原路径
		bool force_override
	) {
		//初始化校验
		init_check();
		//参数校验
		check_string_valid__(OPT::restore_recycled_item, user_father);
		check_string_valid__(OPT::restore_recycled_item, user);
		for (auto& key : recycle_item_path) {
			check_string_valid__(OPT::restore_recycled_item, key);
		}
		for (auto& key : restore_path) {
			check_string_valid__(OPT::restore_recycled_item, key);
		}
		
		//权限校验
		UserCheckResult ucr = check_global_users_value__(OPT::restore_recycled_item, user_father, user);
		
		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);
		
		std::string current_time = get_time_string();
		if (ucr.found_su) {
			check_su_thread_id__();
			restore_recycled_item_(
				user_father,
				user,
				recycle_item_path, 
				restore_path,
				force_override
			);
		}
		//字典锁
		else if (DICT_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::restore_recycled_item, {},
				error_.invalid_operation_error, "No permission to get recycled items.Dict is locked.");
		}
		else {
			if (ucr.found_su_and_hu and (static_cast<int>(ucr.hu_global_permission) == 2)) {
				restore_recycled_item_(
					user_father,
					user,
					recycle_item_path,
					restore_path,
					force_override
				);
			}
			else {
				throw_dict_error(user_father, user, OPT::restore_recycled_item, {},
					error_.invalid_operation_error, "No permission to get recycled items.");
			}
		}
	};

	//=====日志=====
	void Dict::turn_on_log(std::string su) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::turn_on_log;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//根据需要选择
		if (ucr.found_su) {
			check_su_thread_id__();
			if (log_is_running_.load(std::memory_order_acquire)) {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "Log is already running.");
			}
			else {
				run_auto_clean_log__();
				turn_on_log_.store(true, std::memory_order_acquire);
				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					"Success to turn on log."
				);
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to turn on log.");
		}
	};
	void Dict::turn_off_log(std::string su) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::turn_off_log;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//根据需要选择
		if (ucr.found_su) {
			check_su_thread_id__();
			if (log_is_running_.load(std::memory_order_acquire)) {
				stop_auto_clean_log__();
				turn_on_log_.store(false, std::memory_order_acquire);
				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					"Success to turn off log."
				);
			}
			else {

				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "Log is already stop.");
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to turn off log.");
		}
	};
	void Dict::clean_log(std::string su) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::clean_log;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//根据需要选择
		if (ucr.found_su) {
			check_su_thread_id__();
			if (log_is_running_.load(std::memory_order_acquire)) {
				clean_log_items__();
				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					"Success to clean log items"
				);
			}
			else {

				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "Log is already stop. Do not need to clean log items.");
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to clean log items.");
		}
	};
	std::vector<Dict::A_LOG> Dict::get_log(
		std::string su,
		std::string target_user_father,
		std::string target_user
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::get_log;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);
		//根据需要选择
		if (ucr.found_su) {
			check_su_thread_id__();
			if (log_is_running_.load(std::memory_order_acquire)) {
				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					"Success to get log items"
				);
				return get_log_items__(target_user_father, target_user);
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "Log is already stop. Do not need to get log items.");
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to get log items.");
		}
	};
	void Dict::save_log(std::string su, std::string file_path) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::save_log;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//根据需要选择
		if (ucr.found_su) {
			check_su_thread_id__();
			if (log_is_running_.load(std::memory_order_acquire)) {
				save_log__(file_path);
				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					("Success to save log items at path:" + file_path)
				);
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "Log is already stop. Do not need to save log items.");
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to save log items.");
		}
	};
	void Dict::turn_on_auto_save_log(std::string su) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::turn_on_auto_save_log;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//根据需要选择
		if (ucr.found_su) {
			check_su_thread_id__();
			if (auto_save_log_.load(std::memory_order_acquire)) {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "Auto save log is already running.");
			}
			else {
				auto_save_log_.store(true, std::memory_order_release);

				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					"Success to turn on auto save log."
				);
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to turn on auto save log.");
		}
	};
	void Dict::turn_off_auto_save_log(std::string su) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::turn_off_auto_save_log;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//根据需要选择
		if (ucr.found_su) {
			check_su_thread_id__();
			if (auto_save_log_.load(std::memory_order_acquire)) {
				auto_save_log_.store(false, std::memory_order_release);

				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					"Success to turn off auto save log."
				);
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "Auto save log is already stop.");
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to turn off auto save log.");
		}
	};

	//=====用户管理=====
	void Dict::add_user(
		std::string user_father,
		std::string user,
		std::string add_user,
		UserType    add_user_type,
		Permission  permission
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::add_user;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		check_string_valid__(opt, add_user);
		if (add_user_type == UserType::su) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Can not add super user.Super user is unique.");
		}
		else if (add_user_type == UserType::hu) {
			//pass
		}
		else if (add_user_type == UserType::vu) {
			//pass
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Invalid user type.");
		}
		if (permission == Permission::rw) {
			if (add_user_type == UserType::vu) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_operation_error, "Can not set global permission to rw for vu.");
			}
			//pass
		}
		else if (permission == Permission::r_) {
			//pass
		}
		else if (permission == Permission::__) {
			//pass
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Invalid global permission.");
		}


		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//这里会把hu, vu的组合报错排除掉
		globel_allowed_rw(opt, current_time, ucr, user_father, user);

		//读写操作
		if (ucr.found_su) {
			check_su_thread_id__();
			if (add_user_type != UserType::hu) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "Super user only can add hu user.");
			}
			else {
				std::unique_lock lock(users_info_tree_.smtx);
				//检查是否已经存在
				auto uit_h = users_info_tree_.UFT.children_users.find(add_user);
				if (uit_h == users_info_tree_.UFT.children_users.end()) {
					global_user_info_ gui;
					gui.user_father_name = user;
					gui.user_name = add_user;
					gui.listen_num = 0;
					gui.user_type = add_user_type;
					gui.permission = permission;
					gui.user_path_permission_list = {};//权限存储节点映射表
					//gui.children_users;

					// 添加到全局用户树
					users_info_tree_.UFT.children_users.emplace(add_user, std::move(gui));
				}
				else {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "High user already exists.");
				}
			}
		}
		else if (ucr.found_su_and_hu) {
			if (add_user_type != UserType::vu) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "High user and hu user only can add vu user.");
			}
			else {
				std::unique_lock lock(users_info_tree_.smtx);
				//检查hu是否已经存在
				auto uit_h = users_info_tree_.UFT.children_users.find(user);
				if (uit_h == users_info_tree_.UFT.children_users.end()) {
					//防御性编程，通常情况下不会出现这种情况
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "High user not found.");
				}
				else {
					//检查vu是否已经存在
					auto uit_v = uit_h->second.children_users.find(add_user);
					if (uit_v == users_info_tree_.UFT.children_users.end()) {
						global_user_info_ gui;
						gui.user_father_name = user;
						gui.user_name = add_user;
						gui.listen_num = 0;
						gui.user_type = add_user_type;
						gui.permission = permission;
						gui.user_path_permission_list = {};//权限存储节点映射表
						//gui.children_users;

						// 添加到全局用户树
						users_info_tree_.UFT.children_users.emplace(add_user, std::move(gui));
					}
					else {
						throw_dict_error(user_father, user, opt, {},
							error_.invalid_user_error, "Visitor user already exists.");
					}
				}
			}
		}
		else {
			//防御性编程，通常情况下不会出现这种情况,因为通常在globel_allowed_rw就已经排除了这种情况
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_user_error, "operation user pair error or else.");
		}

		//日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};

	void Dict::remove_user(
		std::string user_father,
		std::string user,
		std::string remove_user,
		bool only_remove_from_node,
		std::vector<std::string> path
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::remove_user;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		check_string_valid__(opt, remove_user);
		for (auto& key : path) {
			check_string_valid__(opt, key);
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//这里会把hu, vu的组合报错排除掉
		globel_allowed_rw(opt, current_time, ucr, user_father, user);

		//读写操作
		if (ucr.found_su) {
			check_su_thread_id__();
			//智能锁
			std::unique_lock lock(users_info_tree_.smtx);
			std::unique_lock lock_listen(listeners_.smtx);
			//检查是否已经存在
			auto uit_h = users_info_tree_.UFT.children_users.find(remove_user);
			if (uit_h == users_info_tree_.UFT.children_users.end()) {
				throw_dict_error(user_father, user, opt, {},
					error_.user_not_found_error, "Target remove high user not found.");
			}
			else {
				//无需降权操作，因为UFT已经锁定，无法读取

				//先清理vu
				for (auto [vu_name, vu_info] : uit_h->second.children_users) {
					//清理节点中的信息
					for (auto path : vu_info.user_path_permission_list) {
						try {
							LockedNode locked_node = get_node__(
								opt,
								user_father,
								user,
								Permission::rw,
								path,
								NodeType::any,
								LockType::Write,
								current_time
							);
							//清理节点内监听器
							std::vector<long long int> listen_ids;
							auto& listen_it = locked_node.node->info.event_listen_ml_;
							for (auto& [OPT_EL, L_KEYS] : listen_it) {
								auto REM_KEYS = L_KEYS.find(user + " " + remove_user);
								if (REM_KEYS != L_KEYS.end()) {
									for (auto& [id, event_info] : REM_KEYS->second) {
										listen_ids.push_back(id);
									}
									L_KEYS.erase(REM_KEYS);
								}
							}
							//清理监听器注册表
							for (auto id : listen_ids) {
								listeners_.listen_map_.erase(id);
								recycle_listen_id(id);
							}

							//清理权限信息
							auto permission_it = locked_node.node->info.users_permission.find(user + " " + remove_user);
							if (permission_it != locked_node.node->info.users_permission.end()) {
								locked_node.node->info.users_permission.erase(permission_it);
							}
						}
						catch (...) {

						}
					}
				}
				//清理hu
				for (auto path : uit_h->second.user_path_permission_list) {
					//清理节点中的权限信息
					try {
						LockedNode locked_node = get_node__(
							opt,
							user_father,
							user,
							Permission::rw,
							path,
							NodeType::any,
							LockType::Write,
							current_time
						);
						//清理节点内监听器
						std::vector<long long int> listen_ids;
						auto& listen_it = locked_node.node->info.event_listen_ml_;
						for (auto& [OPT_EL, L_KEYS] : listen_it) {
							auto REM_KEYS = L_KEYS.find(user + " " + remove_user);
							if (REM_KEYS != L_KEYS.end()) {
								for (auto& [id, event_info] : REM_KEYS->second) {
									listen_ids.push_back(id);
								}
								L_KEYS.erase(REM_KEYS);
							}
						}
						//清理监听器注册表
						for (auto id : listen_ids) {
							listeners_.listen_map_.erase(id);
							recycle_listen_id(id);
						}
						//清理权限信息
						auto permission_it = locked_node.node->info.users_permission.find(user + " " + remove_user);
						if (permission_it != locked_node.node->info.users_permission.end()) {
							locked_node.node->info.users_permission.erase(permission_it);
						}
					}
					catch (...) {

					}
				}
				//清理全局用户树
				users_info_tree_.UFT.children_users.erase(uit_h);
			}
		}
		else if (ucr.found_su_and_hu) {
			std::unique_lock lock(users_info_tree_.smtx);
			//检查hu是否已经存在
			auto uit_h = users_info_tree_.UFT.children_users.find(user);
			if (uit_h == users_info_tree_.UFT.children_users.end()) {
				//防御性编程，通常情况下不会出现这种情况
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "High user not found.");
			}
			else {
				//检查vu是否已经存在
				auto uit_v = uit_h->second.children_users.find(remove_user);
				if (uit_v == users_info_tree_.UFT.children_users.end()) {
					throw_dict_error(user_father, user, opt, {},
						error_.user_not_found_error, "Target remove visitor user not found.");
				}
				else {
					//先清理vu在节点中的监听器和权限信息
					for (auto [vu_name, vu_info] : uit_h->second.children_users) {
						//清理节点中的权限信息
						for (auto path : vu_info.user_path_permission_list) {
							try {
								LockedNode locked_node = get_node__(
									opt,
									user_father,
									user,
									Permission::rw,
									path,
									NodeType::any,
									LockType::Write,
									current_time
								);
								//清理节点内监听器
								std::vector<long long int> listen_ids;
								auto& listen_it = locked_node.node->info.event_listen_ml_;
								for (auto& [OPT_EL, L_KEYS] : listen_it) {
									auto REM_KEYS = L_KEYS.find(user + " " + remove_user);
									if (REM_KEYS != L_KEYS.end()) {
										for (auto& [id, event_info] : REM_KEYS->second) {
											listen_ids.push_back(id);
										}
										L_KEYS.erase(REM_KEYS);
									}
								}
								//清理监听器注册表
								for (auto id : listen_ids) {
									listeners_.listen_map_.erase(id);
									recycle_listen_id(id);
								}
								//清理权限信息
								auto permission_it = locked_node.node->info.users_permission.find(user + " " + remove_user);
								if (permission_it != locked_node.node->info.users_permission.end()) {
									locked_node.node->info.users_permission.erase(permission_it);
								}
							}
							catch (...) {

							}
						}
					}
					//清理vu
					uit_h->second.children_users.erase(uit_v);
				}
			}
		}
		else {
			//防御性编程，通常情况下不会出现这种情况,因为通常在globel_allowed_rw就已经排除了这种情况
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_user_error, "operation user pair error or else.");
		}

		//日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};

	//用户交接                                  ！！！待实现，操作数据量过大，依赖的操作计数未实现！！！
	void Dict::transfer_user(
		std::string su,
		std::string transfer_user_father,
		std::string transfer_user,
		std::string transfer_user_new_name
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::transfer_user;

		//参数合法性校验
		check_string_valid__(opt, su);
		check_string_valid__(opt, transfer_user_father);
		check_string_valid__(opt, transfer_user);
		check_string_valid__(opt, transfer_user_new_name);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr_0 = check_global_users_value__(opt, su, su);
		UserCheckResult ucr_1 = check_global_users_value__(opt, transfer_user_father, transfer_user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//读写操作
		if (ucr_0.found_su) {
			check_su_thread_id__();
			if (ucr_1.found_su) {

			}
			else if (ucr_1.found_su_and_hu) {
			
			}
			else if (ucr_1.found_hu_and_vu) {
			
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_user_error, "Target transfer user type error.");
			}

		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "Only super user can transfer user.");
		}

		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			{},
			"Success"
		);
	};

	//交接持有su的线程
	void Dict::transfer_su_keeper_thread(
		std::string su, 
		std::thread::id new_thread_id
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::transfer_su_keeper_thread;

		//参数合法性校验
		check_string_valid__(opt, su);
		if (new_thread_id == std::thread::id()) {
			throw_dict_error(su, su, OPT::any, {}, error_.operation_failed_error,
				"Invalid thread ID");
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//读写操作
		if (ucr.found_su) {
			std::unique_lock lock(dict_name_.smtx);
			if (std::this_thread::get_id() != dict_name_.su_thread_id) {
				throw_dict_error(su, su, OPT::any, {}, error_.operation_failed_error,
					"Super user only can be one thread keep.");
			}
			dict_name_.su_thread_id = new_thread_id;
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "Only super user can transfer su keeper thread.");
		}

		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			{},
			"Success"
		);
	};

	//改变用户等级                              ！！！待实现！！！
	void Dict::change_user_level(
		std::string su_or_hu,
		std::string user,
		UserType    new_level
	) {

	};

	//列出全局用户信息
	std::vector<Dict::user_info> Dict::get_global_users_info(
		std::string user_father, 
		std::string user
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::get_global_users;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		if (ucr.found_su) {
			check_su_thread_id__();
			//智能锁
			std::unique_lock lock(users_info_tree_.smtx);

			std::vector<user_info> user_list;
			for (auto& [hu_name, hu_info] : users_info_tree_.UFT.children_users) {
				user_info ui;
				ui.user_father_name = users_info_tree_.UFT.user_name;
				ui.user_name = hu_name;
				ui.permission = hu_info.permission;
				ui.using_time_permission = false;
				for (auto& [vu_name, vu_info] : hu_info.children_users) {
					user_info ui_c;
					ui_c.user_father_name = users_info_tree_.UFT.user_name;
					ui_c.user_name = vu_name;
					ui_c.permission = vu_info.permission;
					ui_c.using_time_permission = false;
					ui.child_users.insert(std::make_pair(vu_name, ui_c));
				}
				user_list.push_back(ui);
			}
			
			//日志记录
			log_op(
				current_time,
				user_father,
				user,
				opt,
				{},
				"Success"
			);

			return user_list;
		}
		else if (ucr.found_su_and_hu) {
			//智能锁
			std::unique_lock lock(users_info_tree_.smtx);
			auto hu_info = users_info_tree_.UFT.children_users.find(user);
			if (hu_info == users_info_tree_.UFT.children_users.end()) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "High user not found.");
			}
			else {
				std::vector<user_info> user_list;
				user_info ui;
				ui.user_father_name = users_info_tree_.UFT.user_name;
				ui.user_name = user;
				ui.permission = hu_info->second.permission;
				ui.using_time_permission = false;
				for (auto& [vu_name, vu_info] : hu_info->second.children_users) {
					user_info ui_c;
					ui_c.user_father_name = users_info_tree_.UFT.user_name;
					ui_c.user_name = vu_name;
					ui_c.permission = vu_info.permission;
					ui_c.using_time_permission = false;
					ui.child_users.insert(std::make_pair(vu_name, ui_c));
				}
				user_list.push_back(ui);

				//日志记录
				log_op(
					current_time,
					user_father,
					user,
					opt,
					{},
					"Success"
				);

				return user_list;
			}
		}
		else if (ucr.found_hu_and_vu) {
			//智能锁
			std::unique_lock lock(users_info_tree_.smtx);
			auto hu_info = users_info_tree_.UFT.children_users.find(user);
			if (hu_info == users_info_tree_.UFT.children_users.end()) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "High user not found.");
			}
			else {
				std::vector<user_info> user_list;

				auto vu_info = hu_info->second.children_users.find(user);
				if (vu_info == hu_info->second.children_users.end()) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Visitor user not found.");
				}
				else {
					user_info ui;
					ui.user_father_name = user_father;
					ui.user_name = user;
					ui.permission = vu_info->second.permission;
					ui.using_time_permission = false;

					user_list.push_back(ui);

					//日志记录
					log_op(
						current_time,
						user_father,
						user,
						opt,
						{},
						"Success"
					);

					return user_list;
				}
			}
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_user_error, "User not found or else.");
		}
	};
	//列出节点用户信息
	Dict::user_info Dict::get_node_users_info(
		std::string user_father,
		std::string user,
		std::vector<std::string> path
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::get_node_users;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		if (path.empty()) {
			//pass
		}
		else {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}


		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		if (ucr.found_su) {
			check_su_thread_id__();
		}
		
		//读写操作
		{
			LockedNode locked_node = get_node__(
				opt,
				user_father,
				user,
				Permission::r_,
				path,
				NodeType::any,
				LockType::Read,
				current_time
			);
			std::string u_key = user_father + " " + user;
			auto user_node_info = locked_node.node->info.users_permission.find(u_key);

			user_info ui;
			ui.user_father_name = user_father;
			ui.user_name = user;
			ui.permission = user_node_info->second.permission;
			ui.using_time_permission = user_node_info->second.using_time_permission;
			ui.per_is_recursive = user_node_info->second.per_is_recursive;

			//日志记录
			log_op(
				current_time,
				user_father,
				user,
				opt,
				{},
				"Success"
			);

			return ui;
		}
	};

	//=====权限管理=====
	////4种时间权限设置方法 不设置/不设置（永久权限）, 起点/不设置（从某点时间之后有权限）,  不设置/终点（某点时间之前有权限）,  起点/终点（某时间段内有权限）
	////权限时间列表结构为 {{"起点","终点"},{"起点","终点"}}
	////时间点表示方法为"YYYY/MM/DD/HH/MM/SS/mmm/uuu"
	void Dict::set_permission(
		std::string user_father,
		std::string user,
		std::string target_children_user,
		SetType     set_type,
		Permission  permission,
		bool        node_permission_is_recursive,
		bool        using_time_permission,
		std::vector <std::vector<std::string>> node_permission_time_list,
		std::vector<std::string> path
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::set_permission;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		check_string_valid__(opt, target_children_user);
		if (set_type == SetType::global) {
			//pass
		}
		else if (set_type == SetType::node) {
			//pass
		}
		else if (set_type == SetType::global_and_node) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "function set_permission not allowed set_type global_and_node.");
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Unknown set_type.");
		}
		if (permission == Permission::rw) {
			//pass
		}
		else if (permission == Permission::r_) {
			//pass
		}
		else if (permission == Permission::__) {
			//pass
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Unknown permission.");
		}
		if (check_permission_time_list_valid(node_permission_time_list)) {
			//pass
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Invalid permission time list.");
		}
		if (path.empty()) {
			//pass
		}
		else {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr_0 = check_global_users_value__(opt, user_father, user);
		UserCheckResult ucr_1 = check_global_users_value__(opt, user, target_children_user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		globel_allowed_rw(opt, current_time, ucr_0, user_father, user);

		if (set_type == SetType::global) {
			if (ucr_0.found_su) {
				check_su_thread_id__();
				if (ucr_1.found_su) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Super user never allowed set permission.");
				}
				else if (ucr_1.found_su_and_hu) {
					auto hu_info  = users_info_tree_.UFT.children_users.find(target_children_user);
					if (hu_info == users_info_tree_.UFT.children_users.end()) {
						throw_dict_error(user_father, user, opt, {},
							error_.invalid_user_error, "High user not found.");
					}
					else {
						hu_info->second.permission = permission;
					}
				}
				else if (ucr_1.found_hu_and_vu) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
				else {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
			}
			else if (ucr_0.found_su_and_hu) {
				if (ucr_1.found_su) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
				else if (ucr_1.found_su_and_hu) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
				else if (ucr_1.found_hu_and_vu) {
					if (permission == Permission::rw) {
						throw_dict_error(user_father, user, opt, {},
							error_.invalid_operation_error, "Visit user can not set permission rw.");
					}
					else {
						auto hu_info = users_info_tree_.UFT.children_users.find(target_children_user);
						if (hu_info == users_info_tree_.UFT.children_users.end()) {
							throw_dict_error(user_father, user, opt, {},
								error_.invalid_user_error, "High user not found.");
						}
						else {
							auto vu_info = hu_info->second.children_users.find(user);
							if (vu_info == hu_info->second.children_users.end()) {
								throw_dict_error(user_father, user, opt, {},
									error_.invalid_user_error, "Visitor user not found.");
							}
							else {
								vu_info->second.permission = permission;
							}
						}
					}
				}
				else {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
			}
			else if (ucr_0.found_hu_and_vu) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "Visitor user can not set global permission.");
			}
			else {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "User not found or else.");
			}
		}
		else if (set_type == SetType::node) {
			if (ucr_0.found_su) {
				check_su_thread_id__();
				if (ucr_1.found_su) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Super user never allowed set permission.");
				}
				else if (ucr_1.found_su_and_hu) {
					//读写操作
					{
						LockedNode locked_node = get_node__(
							opt,
							user_father,
							user,
							Permission::rw,
							path,
							NodeType::any,
							LockType::Write,
							current_time
						);
						std::string u_key = user + " " + target_children_user;
						// 修改后（自动创建记录）：
						auto& users_permission = locked_node.node->info.users_permission;
						auto it = users_permission.find(u_key);
						if (it == users_permission.end()) {
							// 创建新权限记录
							user_info new_info;
							new_info.permission = permission;
							new_info.using_time_permission = using_time_permission;
							new_info.permission_time_list = node_permission_time_list;
							new_info.per_is_recursive = node_permission_is_recursive;
							users_permission[u_key] = new_info;
						}
						else {
							// 更新现有记录
							it->second.permission = permission;
							it->second.using_time_permission = using_time_permission;
							it->second.permission_time_list = node_permission_time_list;
							it->second.per_is_recursive = node_permission_is_recursive;
						}
					}
				}
				else if (ucr_1.found_hu_and_vu) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
				else {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
			}
			else if (ucr_0.found_su_and_hu) {
				if (ucr_1.found_su) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
				else if (ucr_1.found_su_and_hu) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
				else if (ucr_1.found_hu_and_vu) {
					if (permission == Permission::rw) {
						throw_dict_error(user_father, user, opt, {},
							error_.invalid_operation_error, "Visit user can not set permission rw.");
					}
					else {
						//读写操作
						{
							LockedNode locked_node = get_node__(
								opt,
								user_father,
								user,
								Permission::rw,
								path,
								NodeType::any,
								LockType::Write,
								current_time
							);
							std::string u_key = user + " " + target_children_user;
							auto& users_permission = locked_node.node->info.users_permission;
							auto it = users_permission.find(u_key);
							if (it == users_permission.end()) {
								// 创建新权限记录
								user_info new_info;
								new_info.permission = permission;
								new_info.using_time_permission = using_time_permission;
								new_info.permission_time_list = node_permission_time_list;
								new_info.per_is_recursive = node_permission_is_recursive;
								users_permission[u_key] = new_info;
							}
							else {
								// 更新现有记录
								it->second.permission = permission;
								it->second.using_time_permission = using_time_permission;
								it->second.permission_time_list = node_permission_time_list;
								it->second.per_is_recursive = node_permission_is_recursive;
							}
						}
					}
				}
				else {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_user_error, "Unknow error.");
				}
			}
			else if (ucr_0.found_hu_and_vu) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "Visitor user can not set global permission.");
			}
			else {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_user_error, "User not found or else.");
			}
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "function set_permission not allowed set_type global_and_node.");
		}

		//日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};
	
	//==========字典操作==========
	//=====特殊操作=====
	//=====维护=====
	// 冻结整个字典（进入只读模式，只有su可以进行写操作）
	void Dict::freeze(std::string su) {
		//初始化校验
		init_check();
		check_string_valid__(OPT::freeze, su);
		UserCheckResult ucr = check_global_users_value__(OPT::freeze, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		if (ucr.found_su) {
			check_su_thread_id__();
			if (DICT_FROZEN_LOCK.load(std::memory_order_acquire)) {
				throw_dict_error(su, su, OPT::freeze, {},
					error_.invalid_operation_error, "Dict has been frozen.");
			}
			else {
				DICT_FROZEN_LOCK.store(true, std::memory_order_release);
			}
		}
		else {
			throw_dict_error(su, su, OPT::freeze, {},
				error_.invalid_operation_error, "No permission to freeze operation.");
		}
	};
	// 解冻整个字典
	void Dict::unfreeze(std::string su) {
		//初始化校验
		init_check();
		check_string_valid__(OPT::unfreeze, su);
		UserCheckResult ucr = check_global_users_value__(OPT::unfreeze, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		if (ucr.found_su) {
			check_su_thread_id__();
			if (DICT_FROZEN_LOCK.load(std::memory_order_acquire)) {
				DICT_FROZEN_LOCK.store(false, std::memory_order_release);
			}
			else {
				throw_dict_error(su, su, OPT::unfreeze, {},
					error_.invalid_operation_error, "Dict has been frozen.");
			}
		}
		else {
			throw_dict_error(su, su, OPT::unfreeze, {},
				error_.invalid_operation_error, "No permission to unfreeze operation.");
		}
	};
	//===操作锁===(锁定后拒绝非su的任何操作)
	void Dict::lock_operation(std::string su) {
		//初始化校验
		init_check();
		check_string_valid__(OPT::lock_operation, su);
		UserCheckResult ucr = check_global_users_value__(OPT::lock_operation, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		if (ucr.found_su) {
			check_su_thread_id__();
			if (DICT_LOCK.load(std::memory_order_acquire)) {
				throw_dict_error(su, su, OPT::lock_operation, {},
					error_.invalid_operation_error, "Dict has been locked.");
			}
			else {
				DICT_LOCK.store(true, std::memory_order_release);
			}
		}
		else {
			throw_dict_error(su, su, OPT::lock_operation, {},
				error_.invalid_operation_error, "No permission to lock operation.");
		}
	};
	void Dict::unlock_operation(std::string su) {
		//初始化校验
		init_check();
		check_string_valid__(OPT::unlock_operation, su);
		UserCheckResult ucr = check_global_users_value__(OPT::unlock_operation, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		if (ucr.found_su) {
			check_su_thread_id__();
			if (DICT_LOCK.load(std::memory_order_acquire)) {
				DICT_LOCK.store(false, std::memory_order_release);
			}
			else {
				throw_dict_error(su, su, OPT::unlock_operation, {},
					error_.invalid_operation_error, "Dict has been unlocked.");
			}
		}
		else {
			throw_dict_error(su, su, OPT::unlock_operation, {},
				error_.invalid_operation_error, "No permission to unlock operation.");
		}
	};
	//===字典锁===(锁定后无法对节点操作)
	void Dict::lock_dict(
		std::string su,
		std::vector<std::string> path
	) {	
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::lock_dict;

		//参数合法性校验
		check_string_valid__(opt, su);
		if (path.empty()) {
			//pass
		}
		else {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);


		if (ucr.found_su) {
			check_su_thread_id__();
			//读写操作
			{
				LockedNode locked_node = get_node__(
					opt,
					su,
					su,
					Permission::rw,
					path,
					NodeType::any,
					LockType::Read,
					current_time
				);
				if (locked_node.node->is_locked.load(std::memory_order_acquire)) {
					throw_dict_error(su, su, opt, path,
						error_.invalid_operation_error, "Dict has been locked.");
				}
				else {
					locked_node.node->is_locked.store(true, std::memory_order_release);
				}
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to lock dict.");
		}

		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			path,
			"Success"
		);
	};
	void Dict::unlock_dict(
		std::string su,
		std::vector<std::string> path
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::unlock_dict;

		//参数合法性校验
		check_string_valid__(opt, su);
		if (path.empty()) {
			//pass
		}
		else {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);


		if (ucr.found_su) {
			check_su_thread_id__();
			//读写操作
			{
				LockedNode locked_node = get_node__(
					opt,
					su,
					su,
					Permission::rw,
					path,
					NodeType::any,
					LockType::Read,
					current_time
				);
				if (locked_node.node->is_locked.load(std::memory_order_acquire)) {
					locked_node.node->is_locked.store(true, std::memory_order_release);
				}
				else {
					throw_dict_error(su, su, opt, path,
						error_.invalid_operation_error, "Dict has been unlocked.");
				}
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to unlock dict.");
		}

		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			path,
			"Success"
		);
	};
	//=====拦截=====（拦截后，所有非su的设置为支持拦截的操作都会失败并回滚）（只有这个可以触发回滚）
	//注册拦截（模式：1.点拦截（关卡式，只对未到达的操作有效）、2.路径段拦截（对正在路径段上的操作都有效，逆向路径瞬间拦截（微妙级完成设卡）））,返回注册ID
	long long int Dict::add_intercept(
		std::string su,
		InterceptType intercept_type,
		bool work_now,                      //仅点拦截有效
		std::vector<std::string> point_path,//点拦截路径
		std::vector<std::string> from_path, //起点路径
		std::vector<std::string> to_path    //终点路径
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::add_intercept;

		//参数合法性校验
		check_string_valid__(opt, su);
		if (intercept_type == InterceptType::point_intercept) {
			if (from_path.empty() and to_path.empty()) {
				//pass
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "from_path and to_path are unnecessary when intercept_type is point_intercept.");
			}
			if(point_path.size() > 0){
				for (auto& key : point_path) {
					check_string_valid__(opt, key);
				}
			}
			else {
				//pass
			}
		}
		else if (intercept_type == InterceptType::from_to_intercept) {
			if (work_now) {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "work_now is not allowed when intercept_type is from_to_intercept.");
			}
			if (point_path.empty()) {
				//pass
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "point_path is unnecessary when intercept_type is from_to_intercept.");
			}
			if (from_path.size() > 0) {
				for (auto& key : from_path) {
					check_string_valid__(opt, key);
				}
			}
			else {
				//pass
			}
			if (to_path.size() > 0) {
				for (auto& key : to_path) {
					check_string_valid__(opt, key);
				}
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "to_path is empty.");
			}
			if (from_path.size() < to_path.size()) {
				// 校验父子路径关系
				if (!std::equal(from_path.begin(), from_path.end(), to_path.begin())) {
					throw_dict_error(su, su, opt, {},
						error_.invalid_operation_error,
						"from_path is not a parent of to_path.");
				}
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "from_path is longer than to_path or equal.");
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "intercept_type is invalid.");
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);


		if (ucr.found_su) {
			check_su_thread_id__();
			
			if (intercept_type == InterceptType::point_intercept) {
				long long int PIID;
				//读写操作
				{
					LockedNode locked_node = get_node__(
						opt,
						su,
						su,
						Permission::rw,
						point_path,
						NodeType::any,
						LockType::Unlocked,//不锁定节点，防止锁竞争
						current_time
					);
					if (locked_node.node->is_intercepted.load(std::memory_order_acquire)) {
						throw_dict_error(su, su, opt, point_path,
							error_.invalid_operation_error, "node has been intercepted.");
					}
					else {
						if (work_now) {
							locked_node.node->is_locked.store(true, std::memory_order_release);
						}
						//注册拦截(不移出节点智能锁作用域，防止调用方非法将su赋予多个线程造成非法调用，暴露中间状态)
						std::unique_lock lock(intercept_info_.smtx);

						PIID = add_intercept_id();
						std::vector<std::weak_ptr<Node>> weak_node_list;
						weak_node_list.push_back(locked_node.node);

						intercept_info_.intercept_map_.insert(std::make_pair(PIID, weak_node_list));
					}
				}
				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					point_path,
					"Success"
				);
				return PIID;
			}
			else if (intercept_type == InterceptType::from_to_intercept) {
				long long int FTID;
				//先锁定根节点防止锁竞争
				//读写操作
				{
					LockedNode locked_node = get_node__(
						opt,
						su,
						su,
						Permission::rw,
						{},
						NodeType::any,
						LockType::Unlocked,
						current_time
					);
					locked_node.node->is_locked.store(true, std::memory_order_release);
				}
				//倒序获取节点
				size_t begin_index = from_path.size() - 1;
				size_t end_index = to_path.size() - 1;
				std::vector<std::string> copy_to_path_for_step = to_path;
				std::vector <std::weak_ptr<Node>> weak_node_list;
				for (size_t i = end_index; i >= begin_index; i--) {
					//读写操作
					{
						LockedNode locked_node = get_node__(
							opt,
							su,
							su,
							Permission::rw,
							copy_to_path_for_step,
							NodeType::any,
							LockType::Unlocked,//不锁定节点，防止锁竞争
							current_time
						);
						if (locked_node.node->is_intercepted.load(std::memory_order_acquire)) {
							throw_dict_error(su, su, opt, {},
								error_.invalid_operation_error,
								"Some node has been intercepted.");
						}
						else {
							weak_node_list.push_back(locked_node.node);
						}
					}
					//移除最后一个元素
					copy_to_path_for_step.pop_back();
				}
				//解锁根节点
				//读写操作
				{
					LockedNode locked_node = get_node__(
						opt,
						su,
						su,
						Permission::rw,
						{},
						NodeType::any,
						LockType::Unlocked,//不锁定节点，防止锁竞争
						current_time
					);
					locked_node.node->is_locked.store(false, std::memory_order_release);
				}
				std::unique_lock lock(intercept_info_.smtx);
				FTID = add_intercept_id();
				intercept_info_.intercept_map_.insert(std::make_pair(FTID, weak_node_list));

				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					point_path,
					"Success"
				);
				return FTID;
			}
			else {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, "intercept_type is invalid or else unknow error");
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to add intercept");
		}
	};
	//尝试拦截
	void Dict::turn_on_intercept(
		std::string su,
		long long int intercept_id
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::turn_on_intercept;

		//参数合法性校验
		check_string_valid__(opt, su);
		if (intercept_id < 0) {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "intercept_id is invalid.Maybe it has never been successfully registered.");
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);


		//读写操作
		if (ucr.found_su) {
			check_su_thread_id__();
			//智能锁
			std::unique_lock lock(intercept_info_.smtx);
			auto intercept = intercept_info_.intercept_map_.find(intercept_id);
			if (intercept == intercept_info_.intercept_map_.end()) {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error, 
					"intercept_id is invalid.Maybe it has never been successfully registered.");
			}
			else {
				//读取数据
				std::vector<std::shared_ptr<Node>> shared_ptr_node_list;
				bool is_all_locked = true;
				long long int error_node_index = 0;
				for (long long int i = (intercept->second.size() - 1); i >= 0; i--) {
					if (auto node = intercept->second[i].lock()) {
						//检查是否被拦截
						if (node->is_intercepted.load(std::memory_order_acquire)) {
							is_all_locked = false;
							error_node_index = i;
							break;
						}
						else {
							node->is_intercepted.store(true, std::memory_order_release);
							shared_ptr_node_list.push_back(node);
						}
					}
					else {
						throw_dict_error(su, su, opt, {},
							error_.invalid_operation_error, 
							"When turn on intercept.Some node has been deleted.");
					}
				}
				//如果有节点被拦截，则回滚并抛出异常
				if (!is_all_locked) {
					for (long long int i = shared_ptr_node_list.size(); i > error_node_index; i--) {
						shared_ptr_node_list[i]->is_intercepted.store(false, std::memory_order_release);
					}
					throw_dict_error(su, su, opt, {},
						error_.invalid_operation_error, 
						"When turn on intercept.Some node has been intercepted.");
				}
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to turn on intercept.");
		}

		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			{},
			"Success"
		);
	};
	//停用拦截
	void Dict::turn_off_intercept(
		std::string su,
		long long int intercept_id
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::turn_off_intercept;

		//参数合法性校验
		check_string_valid__(opt, su);
		if (intercept_id < 0) {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "intercept_id is invalid.Maybe it has never been successfully registered.");
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//读写操作
		if (ucr.found_su) {
			check_su_thread_id__();
			//智能锁
			std::unique_lock lock(intercept_info_.smtx);
			auto intercept = intercept_info_.intercept_map_.find(intercept_id);
			if (intercept == intercept_info_.intercept_map_.end()) {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error,
					"intercept_id is invalid.Maybe it has never been successfully registered.");
			}
			else {
				//读取数据
				std::vector<std::shared_ptr<Node>> shared_ptr_node_list;
				bool is_all_node_ok = true;
				for (long long int i = (intercept->second.size() - 1); i >= 0; i--) {
					if (auto node = intercept->second[i].lock()) {
						//检查是否被拦截
						if (node->is_intercepted.load(std::memory_order_acquire)) {
							node->is_intercepted.store(false, std::memory_order_release);
							shared_ptr_node_list.push_back(node);
						}
						else {
							is_all_node_ok = false;
						}
					}
					else {
						throw_dict_error(su, su, opt, {},
							error_.invalid_operation_error,
							"When turn on intercept.Some node has been deleted.");
					}
				}
				//如果有节点被拦截，则抛出异常
				//可能是异常的点拦截解除行为
				if (!is_all_node_ok) {
					throw_dict_error(su, su, opt, {},
						error_.invalid_operation_error,
						//有节点的拦截被异常解除
						"Some node'sintercept was turn off before.");
				}
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to turn on intercept.");
		}

		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			{},
			"Success"
		);
	};
	//删除拦截
	void Dict::del_intercept(
		std::string su,
		long long int intercept_id
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::del_intercept;

		//参数合法性校验
		check_string_valid__(opt, su);
		if (intercept_id < 0) {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "intercept_id is invalid.Maybe it has never been successfully registered.");
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);
		
		if (ucr.found_su){
			check_su_thread_id__();
			std::unique_lock lock(intercept_info_.smtx);
			auto intercept = intercept_info_.intercept_map_.find(intercept_id);
			if (intercept == intercept_info_.intercept_map_.end()) {
				throw_dict_error(su, su, opt, {},
					error_.invalid_operation_error,
					"intercept_id is invalid.Maybe it has never been successfully registered.");
			}
			else {
				turn_off_intercept(su, intercept_id);
				intercept_info_.intercept_map_.erase(intercept);
				recycle_intercept_id(intercept_id);
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to delete intercept.");
		}

		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			{},
			"Success"
		);
	};
	//拦截查询
	bool Dict::is_intercepted(
		std::string su,
		std::vector<std::string> path
	) {
		//初始化校验
		init_check();
		//操作类型设置
		OPT opt = OPT::is_intercepted;

		//参数合法性校验
		check_string_valid__(opt, su);
		if (path.empty()) {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		if (ucr.found_su) {
			check_su_thread_id__();
			//读写操作
			{
				LockedNode locked_node = get_node__(
					opt,
					su,
					su,
					Permission::r_,
					path,
					NodeType::any,
					LockType::Unlocked,
					current_time
				);

				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					"Success"
				);

				return locked_node.node->is_intercepted;
			}
		}
		else {
			throw_dict_error(su, su, opt, {},
				error_.invalid_operation_error, "No permission to delete intercept.");
		}
	};
	//列举拦截
	std::vector<Dict::a_intercept_info> Dict::list_intercept(
		std::string su
	) {
		throw_dict_error(su, su, OPT::search, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//===杂项===
	//清空dict（保留全局信息）                                                    ！！！待实现！！！
	void Dict::clear(std::string su) {

	};
	//注销dict（删除所有信息，退回到未初始化状态）                                ！！！待实现！！！
	void Dict::log_of(std::string su) {

	};

	//===节点操作===
	//增（总节点/ID上限为922 3372 0368 5477 5807）
	void Dict::add(
		std::string user_father,
		std::string user,
		add_type    add_type,
		std::any    value,
		std::vector<std::string> path,
		bool        lock_now      //仅su可用
	) {
		//初始化校验
		init_check();

		//操作类型设置
		OPT opt = OPT::add;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		if (add_type == add_type::dict) {
			//pass
		}
		else if (add_type == add_type::value) {
			//pass
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "add_type is invalid");
		}
		for (auto& key : path) {
			check_string_valid__(opt, key);
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//su线程校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		//读写操作
		{
			//获取工作路径
			std::vector<std::string> work_path = path;
			work_path.pop_back();
			std::string key = path.back();

			LockedNode locked_node = get_node__(
				opt,
				user_father,
				user,
				Permission::rw,
				work_path,
				NodeType::any,
				LockType::Write,
				current_time
			);

			//操作计数
			operation_counter oc = operation_counter(this, oc_type::node_operation_counter, &locked_node.node->node_op_counter_);

			if (add_type == add_type::dict) {
				
				//检查重名节点
				auto add_node = locked_node.node->info.children.find(key);

				if (add_node != locked_node.node->info.children.end()) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_operation_error, "The key already exists.");
				}
				else {
					if (!ucr.found_su) {
						//节点信息校验
						auto user_info_ = add_node->second->info.users_permission.find(std::string(user_father + " " + user));
						if (add_node->second->is_broken.load(std::memory_order_acquire)) {
							throw_dict_error(user_father, user, opt, {},
								error_.invalid_operation_error, "The node has been broken.");
						}
						else if (add_node->second->is_locked.load(std::memory_order_acquire)) {
							throw_dict_error(user_father, user, opt, {},
								error_.invalid_operation_error, "The node has been locked.");
						}
						else if (add_node->second->is_intercepted.load(std::memory_order_acquire)) {
							throw_dict_error(user_father, user, opt, {},
								error_.invalid_operation_error, "The node has been intercepted.");
						}
						else if (user_info_->second.permission != Permission::rw) {
							throw_dict_error(user_father, user, opt, {},
								error_.invalid_operation_error,
								"No permission to add node.Because have a same name node and have no permission to modify it.");
						}
						else if (user_info_->second.permission == Permission::rw) {
							//检查时间权限
							check_time_permission_valid(user_info_->second, current_time);
						}
					}
					else {
						//创建新节点
						std::string time_string = get_time_string();
						std::shared_ptr<Node> new_node = std::make_shared<Node>();
						new_node->info.is_dict = true;
						add_node_id__(new_node->info.node_id);
						new_node->info.create_time = time_string;
						new_node->info.key = key;
						//new_node->info.value; //不使用
						new_node->is_intercepted.store(false, std::memory_order_release);
						new_node->is_broken.store(false, std::memory_order_release);

						if (ucr.found_su and lock_now) {
							new_node->is_locked.store(true, std::memory_order_release);
						}
						else {
							new_node->is_locked.store(false, std::memory_order_release);
						}
						//插入到父节点
						locked_node.node->info.children.insert(
							std::make_pair(key, new_node)
						);
						//触发监听
						node_trigger_listeners(
							user_father,
							user,
							opt,
							current_time,
							path,
							key,
							std::string("NULL"),
							value,
							std::string("NULL"),
							locked_node.node
						);
					}
				}
			}
			else if (add_type == add_type::value) {
				//检查重名值节点
				auto add_node = locked_node.node->info.children.find(key);
				if (add_node!= locked_node.node->info.children.end()) {
					throw_dict_error(user_father, user, opt, {},
						error_.invalid_operation_error, "The key already exists.");
				}
				else {
					//创建新节点
					std::string time_string = get_time_string();
					std::shared_ptr<Node> new_node = std::make_shared<Node>();
					new_node->info.is_dict = false;
					add_node_id__(new_node->info.node_id);
					new_node->info.create_time = time_string;
					new_node->info.key = key;
					new_node->info.value = value;
					new_node->is_intercepted.store(false, std::memory_order_release);
					new_node->is_broken.store(false, std::memory_order_release);
					
					if (ucr.found_su and lock_now) {
						new_node->is_locked.store(true, std::memory_order_release);
					}
					else {
						new_node->is_locked.store(false, std::memory_order_release);
					}
					//插入到父节点
					locked_node.node->info.children.insert(
						std::make_pair(key, new_node)
					);
					//触发监听
					node_trigger_listeners(
						user_father,
						user,
						opt,
						current_time,
						path,
						key,
						std::string("NULL"),
						value,
						std::string("NULL"),
						locked_node.node
					);
				}
			}
			else {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_operation_error, "add_type is invalid");
			}
		}
		//日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};
	//批量增（总节点上限/ID为上限为922 3372 0368 5477 5807）
	void Dict::add_batch(
		std::string user_father,
		std::string user,
		add_type    add_type,
		const std::vector<std::pair<std::string, std::any>>& key_value_list,
		std::vector<std::string> parent_path,
		bool        lock_now
	) {
		// 1. 初始化校验
		init_check();

		// 2. 操作类型设置
		OPT opt = OPT::add_batch; // 需在OPT枚举中新增add_batch类型

		// 3. 参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		if (add_type != add_type::dict && add_type != add_type::value) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "add_type is invalid");
		}
		for (const auto& kv : key_value_list) {
			check_string_valid__(opt, kv.first);
		}
		for (auto& key : parent_path) {
			check_string_valid__(opt, key);
		}

		// 4. 获取操作时间
		std::string current_time = get_time_string();

		// 5. 权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		// 6. 获取父节点写锁
		std::vector<std::string> work_path = parent_path;
		LockedNode locked_node = get_node__(
			opt,
			user_father,
			user,
			Permission::rw,
			work_path,
			NodeType::dict, // 父节点必须是字典类型
			LockType::Write, // 需要写锁
			current_time
		);

		// 7. 操作计数器
		operation_counter oc(this, oc_type::node_operation_counter, &locked_node.node->node_op_counter_);

		// 8. 预检查所有key是否已存在
		for (const auto& kv : key_value_list) {
			const std::string& key = kv.first;
			if (locked_node.node->info.children.find(key) != locked_node.node->info.children.end()) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_operation_error,
					"Key '" + key + "' already exists in parent node");
			}
		}

		// 9. 批量创建节点
		for (const auto& kv : key_value_list) {
			const std::string& key = kv.first;
			const std::any& value = kv.second;

			std::shared_ptr<Node> new_node = std::make_shared<Node>();
			new_node->info.is_dict = (add_type == add_type::dict);
			add_node_id__(new_node->info.node_id);
			new_node->info.create_time = current_time;
			new_node->info.key = key;
			new_node->info.value = (add_type == add_type::dict) ? std::any(std::string("NULL")) : value;
			new_node->is_intercepted.store(false, std::memory_order_release);
			new_node->is_broken.store(false, std::memory_order_release);
			new_node->is_locked.store((ucr.found_su && lock_now), std::memory_order_release);

			// 插入到父节点
			locked_node.node->info.children.emplace(key, new_node);

			// 10. 触发单个节点监听
			std::vector<std::string> full_path = parent_path;
			full_path.push_back(key);
			node_trigger_listeners(
				user_father,
				user,
				OPT::add, // 触发单节点添加事件
				current_time,
				full_path,
				key,
				std::string("NULL"), // 旧值
				key,                 // 新值
				std::string("NULL"), // 旧类型
				locked_node.node
			);
		}

		// 11. 日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};
	//删
	void Dict::del(
		std::string user_father,
		std::string user,
		std::vector<std::string> path
	) {
		// 1. 初始化校验
		init_check();

		// 2. 操作类型设置
		OPT opt = OPT::del; // 需在OPT枚举中新增add_batch类型

		// 3. 参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		if (path.empty()) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Root node cannot be deleted by function 'del'.");
		}
		else {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}
		

		// 4. 获取操作时间
		std::string current_time = get_time_string();

		// 5. 权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		// 获取工作路径
		std::vector<std::string> work_path = path;
		work_path.pop_back();
		std::string key = path.back();

		LockedNode locked_node = get_node__(
			opt,
			user_father,
			user,
			Permission::rw,
			work_path,
			NodeType::dict,
			LockType::Write,
			current_time
		);

		operation_counter oc = operation_counter(this, oc_type::node_operation_counter, &locked_node.node->node_op_counter_);

		// 检查节点是否存在
		auto del_node_it = locked_node.node->info.children.find(key);
		if (del_node_it == locked_node.node->info.children.end()) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "The key does not exist.");
		}

		// 获取被删除节点
		std::shared_ptr<Node> del_node = del_node_it->second;

		// 处理回收站重名问题
		std::string recycle_key = key;
		int counter = 0;
		while (locked_node.node->info.del_children.find(recycle_key) !=
			locked_node.node->info.del_children.end()) {
			recycle_key = "RECYCLE_" + std::to_string(counter++) + "_" + key;
		}

		// 设置节点删除时间
		del_node->info.del_time = current_time;

		// 移动到父节点的del_children
		locked_node.node->info.del_children.emplace(recycle_key, del_node);

		// 从父节点的children中移除
		locked_node.node->info.children.erase(del_node_it);

		// 加入回收站系统
		join_recycle__(
			user_father,
			user,
			path,
			locked_node.node,  // 父节点指针
			recycle_key,       // 回收站中的key（可能重命名）
			del_node->info.node_id
		);

		// 触发监听事件
		node_trigger_listeners(
			user_father,
			user,
			opt,
			current_time,
			path,
			key,
			"NULL",
			"NULL",
			"NULL",
			locked_node.node
		);

		// 日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};
	//批量删（仅允许同一dict节点下批量删，跨路径删除非法）
	void Dict::del_batch(
		std::string user_father,
		std::string user,
		std::vector<std::vector<std::string>> items_path_list
	) {
		// 1. 初始化校验
		init_check();

		// 2. 操作类型设置
		OPT opt = OPT::del_batch;

		// 3. 参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		for (auto& path : items_path_list) {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}

		// 4. 检查所有路径是否在同一父节点下
		if (items_path_list.empty()) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Empty items_path_list");
		}

		std::vector<std::string> common_path;
		for (size_t i = 0; i < items_path_list.size(); i++) {
			if (items_path_list[i].empty()) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_operation_error, "Empty path in items_path_list");
			}

			// 获取父路径和工作路径
			std::vector<std::string> work_path = items_path_list[i];
			work_path.pop_back();

			if (i == 0) {
				common_path = work_path;
			}
			else if (work_path != common_path) {
				throw_dict_error(user_father, user, opt, {},
					error_.invalid_operation_error,
					"All keys must be under the same parent node");
			}
		}

		// 5. 获取操作时间
		std::string current_time = get_time_string();

		// 6. 权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		// 7. 获取父节点写锁
		LockedNode locked_node = get_node__(
			opt,
			user_father,
			user,
			Permission::rw,
			common_path,
			NodeType::dict,
			LockType::Write,
			current_time
		);

		// 8. 操作计数器
		operation_counter oc(this, oc_type::node_operation_counter, &locked_node.node->node_op_counter_);

		// 9. 预检查所有key是否存在
		std::vector<std::pair<std::string, std::shared_ptr<Node>>> nodes_to_delete;
		nodes_to_delete.reserve(items_path_list.size());

		for (auto& path : items_path_list) {
			std::string key = path.back();
			auto it = locked_node.node->info.children.find(key);
			if (it == locked_node.node->info.children.end()) {
				throw_dict_error(user_father, user, opt, path,
					error_.invalid_operation_error,
					"Key '" + key + "' does not exist");
			}
			nodes_to_delete.emplace_back(key, it->second);
		}

		// 10. 批量删除节点
		for (auto& [key, node] : nodes_to_delete) {
			// 处理回收站重名问题
			std::string recycle_key = key;
			int counter = 0;
			while (locked_node.node->info.del_children.find(recycle_key) !=
				locked_node.node->info.del_children.end()) {
				recycle_key = "RECYCLE_" + std::to_string(counter++) + "_" + key;
			}

			// 设置删除时间
			node->info.del_time = current_time;

			// 移动到父节点的del_children
			locked_node.node->info.del_children.emplace(recycle_key, node);

			// 从父节点的children中移除
			locked_node.node->info.children.erase(key);

			// 构建完整路径
			std::vector<std::string> full_path = common_path;
			full_path.push_back(key);

			// 加入回收站
			join_recycle__(
				user_father,
				user,
				full_path,
				locked_node.node,  // 父节点指针
				recycle_key,       // 回收站中的key
				node->info.node_id
			);

			// 触发监听事件
			node_trigger_listeners(
				user_father,
				user,
				opt,
				current_time,
				full_path,
				key,
				"NULL",
				"NULL",
				"NULL",
				locked_node.node
			);
		}

		// 11. 日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};
	//改
	void Dict::set(
		std::string user_father,
		std::string user,
		set_type    set_type,             //仅value枚举可用
		std::any    new_value,            // 仅值节点可用
		std::vector<std::string> path,
		bool        lock_now             // 仅su可用，不会报错重复锁定
	) {
		//初始化校验
		init_check();

		//操作类型设置
		OPT opt = OPT::set;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		if (set_type == set_type::value) {
			//pass
		}
		else if (set_type == set_type::dict) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "set_type is invalid");
		}
		else {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "set_type is invalid");
		}
		if (path.empty()) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Root node cannot be modified by function'set'.");
		}
		else {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//su线程校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		//读写操作
		{
			LockedNode locked_node = get_node__(
				opt,
				user_father,
				user,
				Permission::rw,
				path,
				NodeType::value,
				LockType::Write,
				current_time
			);

			//操作计数
			operation_counter oc = operation_counter(this, oc_type::node_operation_counter, &locked_node.node->node_op_counter_);

			std::any old_value = locked_node.node->info.value;

			locked_node.node->info.value = new_value;
			
			//触发监听
			node_trigger_listeners(
				user_father,
				user,
				opt,
				current_time,
				path,
				"NULL",
				old_value,
				new_value,
				"NULL",
				locked_node.node
			);
		}
		//日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};

	//批量改（仅允许同一dict节点下批量改，跨路径修改非法）
	void Dict::set_batch(
		std::string user_father,
		std::string user,
		const std::vector < std::pair<std::string, std::any>> set_list,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::set_batch, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//查
	std::any Dict::get_value(
		std::string user_father,
		std::string user,
		std::vector<std::string> path
	) {
		//初始化校验
		init_check();

		//操作类型设置
		OPT opt = OPT::get_value;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		if (path.empty()) {
			throw_dict_error(user_father, user, opt, {},
				error_.invalid_operation_error, "Root node cannot be operated by function 'get_value'.");
		}
		else {
			for (auto& key : path) {
				check_string_valid__(opt, key);
			}
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//su线程校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		//读写操作
		{
			LockedNode locked_node = get_node__(
				opt,
				user_father,
				user,
				Permission::rw,
				path,
				NodeType::value,
				LockType::Write,
				current_time
			);

			//操作计数
			operation_counter oc = operation_counter(this, oc_type::node_operation_counter, &locked_node.node->node_op_counter_);

			std::any old_value = locked_node.node->info.value;

			//触发监听
			node_trigger_listeners(
				user_father,
				user,
				opt,
				current_time,
				path,
				"NULL",
				old_value,
				"NULL",
				"NULL",
				locked_node.node
			);

			//日志记录
			log_op(
				current_time,
				user_father,
				user,
				opt,
				{},
				"Success"
			);

			return old_value;
		}
	};
	//移（其中一个路径为另一个路径的子集时无效（如：/a/b/c/d 移到 /a/b/c/d/e/f））
	void Dict::move(
		std::string user_father,
		std::string user,
		bool overwrite,//是否覆盖目标路径
		std::vector<std::string> path,
		std::vector<std::string> target_path
	) {
		throw_dict_error(user_father, user, OPT::move, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//复制（内部复制移动）
	void Dict::copy_to(
		std::string user_father,
		std::string user,
		bool overwrite,//是否覆盖目标路径
		std::vector<std::string> path,
		std::vector<std::string> target_path
	) {
		throw_dict_error(user_father, user, OPT::copy_to, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//搜索
	std::vector <std::vector<std::string>> Dict::search(
		std::string user_father,
		std::string user,
		std::string key,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::search, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//=====快捷方式=====
	//软链接
	void Dict::add_link(
		std::string user_father,
		std::string user,
		std::vector<std::string> path,
		std::vector<std::string> target_path
	) {
		throw_dict_error(user_father, user, OPT::search, {},
			error_.invalid_operation_error, "Not supported function.");
	};

	//=====对外方法=====
	//只有基本信息的拷贝（返回的结构体里的permission为当前操作者动态计算出的权限）
	Dict::node_info Dict::get_dict(
		std::string user_father,
		std::string user,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::get_dict, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//含元数据的完整拷贝（会返回包含全局权限信息、节点权限、基本数据、关闭回收站的Dict（已回收部分不会被拷贝））
	Dict Dict::copy_dict(
		std::string user_father,
		std::string user,
		int    max_depth,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::copy_dict, {},
			error_.invalid_operation_error, "Not supported function.");
	};

	//=====dict运算=====
	//相等判断
	bool Dict::equal(
		std::string user_father,
		std::string user,
		std::vector<std::string> path_0,
		std::vector<std::string> path_1
	) {
		throw_dict_error(user_father, user, OPT::equal, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//容量计算
	int Dict::size(
		std::string user_father,
		std::string user,
		bool is_recursive,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::size, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//深度计算（计算path末端之后的深度）
	int Dict::depth(
		std::string user_father,
		std::string user,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::depth, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//大小计算
	long long int Dict::size_bytes(
		std::string user_father,
		std::string user,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::size_bytes, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//存在性判断
	bool Dict::exist(
		std::string user_father,
		std::string user,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::exist, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//列举
	std::vector<Dict::node_info> Dict::list(
		std::string user_father,
		std::string user,
		bool is_recursive,
		std::vector<std::string> path
	) {
		throw_dict_error(user_father, user, OPT::list, {},
			error_.invalid_operation_error, "Not supported function.");
	};

	//=====监听=====
	// 这里给予vu监听写特权，在hu有rw，vu有r_时，vu可以写入和删除监听
	
	//监听字典变化（返回监听ID，用于取消监听）
	long long int Dict::add_listen( //总计407行
		std::string user_father,
		std::string user,
		std::string listen_user_father,
		std::string listen_user,
		ListenType  listen_type,
		bool work_now,
		std::vector<std::string> path,
		OPT listen_operation_type,
		std::vector<std::vector<std::string>> permission_time_list,//和时间区间权限类似的功能，用于精确控制监听范围
		bool is_disposable,                         //控制一次性监听和持久监听，一次性监听触发后销毁，可以在触发前取消监听，触发后取消注册方会收到报错
		std::function<void(operation_info_bag op_bag, std::any old_value, std::vector<std::any>&)> callback //回调函数(操作数据包，旧值，私有长效数据空间)
	) {
		//初始化校验
		init_check();
		//校验参数合法性
		check_string_valid__(OPT::add_listen, user_father);
		check_string_valid__(OPT::add_listen, user);
		check_string_valid__(OPT::add_listen, listen_user_father);
		check_string_valid__(OPT::add_listen, listen_user);
		if (path.empty()) {
			//pass
		}
		else {
			for (auto& key : path) {
				check_string_valid__(OPT::add_listen, key);
			}
		}
		if (!check_permission_time_list_valid(permission_time_list)) {
			throw_dict_error(user_father, user, OPT::add_listen, path,
				error_.invalid_operation_error, "Invalid time format.");
		}
		
		//智能锁
		std::unique_lock lock_0(user_listen_quota_.smtx);
		//校验监听器数量是否已经到达上限
		if (user_listen_quota_.quotal_num == user_listen_quota_.max_listen_num) {
			throw_dict_error(user_father, user, OPT::add_listen, path,
				error_.invalid_operation_error,
				"The number of listens has reached the total upper limit.");
		}

		std::string current_time = get_time_string();

		//用户名参数正确判断与组合查询
		UserCheckResult ucr = check_global_users_value__(OPT::add_listen, user_father, user);
		UserCheckResult l_ucr = check_global_users_value__(OPT::add_listen, listen_user_father, listen_user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//su线程ID校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		//操作锁
		if (!ucr.found_su and DICT_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::add_listen, path,
				error_.invalid_operation_error, "Dict has been locked operation.");
		}
		
		//冻结锁
		if (!ucr.found_su and DICT_FROZEN_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::add_listen, path,
				error_.invalid_operation_error, "You do not have permission to add listen. Dict has been frozen.");
		}

		//键合成
		std::string key = user_father + " " + user;
		std::string l_key = listen_user_father + " " + listen_user;

		// ===== 操作类型黑名单检查 =====
		static const std::set<OPT> non_listenable_operations = {
			// 监听管理操作
			OPT::add_listen,
			OPT::start_listen,
			OPT::stop_listen,
			OPT::del_listen,
			OPT::search_listen,

			// 日志操作
			OPT::turn_on_log,
			OPT::turn_off_log,
			OPT::clean_log,
			OPT::get_log,
			OPT::save_log,
			OPT::turn_on_auto_save_log,
			OPT::turn_off_auto_save_log,

			// 回收站操作
			OPT::turn_on_auto_clean_recycle,
			OPT::turn_off_auto_clean_recycle,
			OPT::clean_recycle,
			OPT::get_recycled_items,
			OPT::restore_recycled_item,

			// 权限管理
			OPT::set_permission,
			OPT::add_user,
			OPT::remove_user,
			OPT::transfer_user,
			OPT::change_user_level,
			OPT::get_global_users,
			OPT::get_node_users,

			// 系统锁定/冻结
			OPT::freeze,
			OPT::unfreeze,
			OPT::lock_operation,
			OPT::unlock_operation,
			OPT::lock_dict,
			OPT::unlock_dict,

			// 拦截系统
			OPT::add_intercept,
			OPT::turn_on_intercept,
			OPT::turn_off_intercept,
			OPT::del_intercept,
			OPT::is_intercepted,
			OPT::list_intercept,

			// 字典生命周期
			OPT::clear,
			OPT::log_of,

			// 持久化
			OPT::dict_to_bit,
			OPT::bit_to_dict,
			OPT::dict_to_json,
			OPT::json_to_dict,

			// 原子操作
			OPT::atomic_operation
		};

		// 检查操作类型是否在黑名单中
		if (non_listenable_operations.find(listen_operation_type) != non_listenable_operations.end()) {
			std::string error_msg = "Operation type " + std::to_string(static_cast<int>(listen_operation_type)) +
				" is not allowed for listening";
			throw_dict_error(
				user_father,
				user,
				OPT::add_listen,
				path,
				error_.invalid_operation_error,
				error_msg
			);
		}

		// 检查是否为任意操作类型
		if (listen_operation_type == OPT::any) {
			throw_dict_error(
				user_father,
				user,
				OPT::add_listen,
				path,
				error_.invalid_operation_error,
				"OPT::any is not allowed for listening"
			);
		}

		if (listen_type == ListenType::global) {
			//校验是否有权限
			if (ucr.found_su_and_hu and (ucr.hu_global_permission != Permission::rw)
				or
				(ucr.found_hu_and_vu and ((ucr.hu_global_permission != Permission::rw)or(ucr.vu_global_permission == Permission::r_)))) {
				throw_dict_error(user_father, user, OPT::add_listen, path,
					error_.permission_not_enough,
					"You do not have permission to add global listen.");
			}
			else {
				//智能锁
				std::shared_lock lock(listeners_.smtx);

				//校验是否到达user监听上限
				if ((ucr.found_su and (user_listen_quota_.su_quotal_num == user_listen_quota_.su_max_listen_num))
					or (ucr.found_su_and_hu and (user_listen_quota_.hu_quotal_num == user_listen_quota_.hu_max_listen_num))
					or (ucr.found_hu_and_vu and (user_listen_quota_.vu_quotal_num == user_listen_quota_.vu_max_listen_num))
				){
					throw_dict_error(user_father, user, OPT::add_listen, path,
						error_.invalid_operation_error,
						"The number of listens has reached the user's upper limit.");
				}

				//校验是否重复注册无法实现，std::function的内容无法比较
				//智能锁
				std::unique_lock lock_1(global_listeners_.smtx);

				auto was_listened = global_listeners_.global_listen_map_;

				long long int id = add_listen_id();

				global_listen_info_bag gli_bag;
				gli_bag.listen_id = id;
				gli_bag.is_work = work_now;
				gli_bag.listen_operation_type = listen_operation_type;
				gli_bag.permission_time_list = permission_time_list;
				gli_bag.is_disposable = is_disposable;
				gli_bag.callback = std::move(callback);
				

				//校验前置注册信息是否足够并注册
				auto event_listen_list = global_listeners_.global_listen_map_;
				auto OPT_EL = event_listen_list.find(static_cast<int>(listen_operation_type));
				if (OPT_EL == event_listen_list.end()) {
					auto& opt_el = event_listen_list[static_cast<int>(listen_operation_type)];
					auto& listener_el = opt_el[l_key];
					listener_el[id] = std::move(gli_bag);
				}
				else {
					auto& listener_el = OPT_EL->second[l_key];
					listener_el[id] = std::move(gli_bag);
				}

				//增加计数
				if (ucr.found_su) {
					user_listen_quota_.su_quotal_num++;
				}
				else if (ucr.found_su_and_hu) {
					user_listen_quota_.hu_quotal_num++;
				}
				else if (ucr.found_hu_and_vu) {
					user_listen_quota_.vu_quotal_num++;
				}
				user_listen_quota_.quotal_num++;

				//放入注册表
				listen_info_bag li_bag;
				li_bag.listen_type = listen_type;
				li_bag.user_father = listen_user_father;
				li_bag.user = listen_user;
				li_bag.listen_operation_type = listen_operation_type;
				//li_bag.listen_node_ptr; 全局监听用不到这个
				li_bag.OPT_ID = static_cast<int>(listen_operation_type);
				li_bag.listened_user_father_and_user = l_key;
				li_bag.is_work = work_now;
				li_bag.listened_path = path;
				li_bag.permission_time_list = permission_time_list;
				li_bag.is_disposable = is_disposable;

				listeners_.listen_map_[gli_bag.listen_id] = li_bag;

				//禁止触发监听，触发容易导致递归

				//日志记录
				log_op(
					current_time,
					user_father,
					user,
					OPT::add_listen,
					{},
					"Success"
				);

				return gli_bag.listen_id;
			}
		}
		else {
			//校验是否到达user监听上限
			if ((ucr.found_su and (user_listen_quota_.su_quotal_num >= user_listen_quota_.su_max_listen_num))
				or (ucr.found_su_and_hu and (user_listen_quota_.hu_quotal_num >= user_listen_quota_.hu_max_listen_num))
				or (ucr.found_hu_and_vu and (user_listen_quota_.vu_quotal_num >= user_listen_quota_.vu_max_listen_num))
				) {
				throw_dict_error(user_father, user, OPT::add_listen, path,
					error_.invalid_operation_error,
					"The number of listens has reached the user's upper limit.");
			}

			if(ucr.found_su or ucr.found_su_and_hu){
				LockedNode locked_node = get_node__(
					OPT::add_listen,
					user_father,
					user,
					Permission::rw,
					path,
					NodeType::any,
					LockType::Write,
					current_time
				);
				//智能锁
				std::shared_lock lock(listeners_.smtx);

				//校验是否重复注册无法实现，std::function的内容无法比较

				long long int id = add_listen_id();

				event_info ei;
				ei.listen_id = id;
				ei.is_work = work_now;
				ei.is_disposable = is_disposable;
				ei.listen_type = listen_type;
				ei.listen_operation_type = listen_operation_type;
				ei.permission_time_list = permission_time_list;
				ei.callback = std::move(callback);

				//校验前置注册信息是否足够
				auto event_listen_list = locked_node.node->info.event_listen_ml_;
				auto OPT_EL = event_listen_list.find(static_cast<int>(listen_operation_type));
				if (OPT_EL == event_listen_list.end()) {
					auto& opt_el = event_listen_list[static_cast<int>(listen_operation_type)];
					auto& listener_el = opt_el[l_key];
					listener_el[ei.listen_id] = std::move(ei);
				}
				else {
					auto& listener_el = OPT_EL->second[l_key];
					listener_el[ei.listen_id] = std::move(ei);
				}
				//放入注册表
				listen_info_bag li_bag;
				li_bag.user_father = listen_user_father;
				li_bag.user = listen_user;
				li_bag.listen_operation_type = listen_operation_type;
				li_bag.listen_node_ptr = locked_node.node;
				li_bag.is_work = work_now;
				li_bag.listened_path = path;
				li_bag.permission_time_list = permission_time_list;
				li_bag.is_disposable = is_disposable;

				listeners_.listen_map_[id] = li_bag;

				//增加计数
				if (ucr.found_su) {
					user_listen_quota_.su_quotal_num++;
				}
				else if (ucr.found_su_and_hu) {
					user_listen_quota_.hu_quotal_num++;
				}
				user_listen_quota_.quotal_num++;

				return ei.listen_id;
			}
			//当参数为hu, vu时，给get_node__传入r_权限，这样vu的权限校验就会通过
			else if (ucr.found_hu_and_vu) {
				LockedNode locked_node = get_node__(
					OPT::add_listen,
					user_father,
					user,
					Permission::r_,
					path,
					NodeType::any,
					LockType::Write,
					current_time
				);
				//智能锁
				std::shared_lock lock(listeners_.smtx);

				//校验是否重复注册无法实现，std::function的内容无法比较

				long long int id = add_listen_id();

				event_info ei;
				ei.listen_id = id;
				ei.is_work = work_now;
				ei.is_disposable = is_disposable;
				ei.listen_type = listen_type;
				ei.listen_operation_type = listen_operation_type;
				ei.permission_time_list = permission_time_list;
				ei.callback = std::move(callback);

				//校验前置注册信息是否足够
				auto event_listen_list = locked_node.node->info.event_listen_ml_;
				auto OPT_EL = event_listen_list.find(static_cast<int>(listen_operation_type));
				if (OPT_EL == event_listen_list.end()) {
					auto& opt_el = event_listen_list[static_cast<int>(listen_operation_type)];
					auto& listener_el = opt_el[l_key];
					listener_el[ei.listen_id] = std::move(ei);
				}
				else {
					auto& listener_el = OPT_EL->second[l_key];
					listener_el[id] = std::move(ei);
				}
				//放入注册表
				listen_info_bag li_bag;
				li_bag.listen_type = listen_type;
				li_bag.user_father = listen_user_father;
				li_bag.user = listen_user;
				li_bag.listen_operation_type = listen_operation_type;
				li_bag.listen_node_ptr = locked_node.node;
				li_bag.OPT_ID = static_cast<int>(listen_operation_type);
				li_bag.listened_user_father_and_user = l_key;
				li_bag.is_work = work_now;
				li_bag.listened_path = path;
				li_bag.permission_time_list = permission_time_list;
				li_bag.is_disposable = is_disposable;

				listeners_.listen_map_[id] = li_bag;

				//增加计数
				user_listen_quota_.vu_quotal_num++;
				user_listen_quota_.quotal_num++;

				//禁止触发监听，触发容易导致递归

				//日志记录
				log_op(
					current_time,
					user_father,
					user,
					OPT::add_listen,
					{},
					"Success"
				);

				return ei.listen_id;
			}
			
		}
		//实际不应该执行到这里
		return -1;
	};
	//启用监听
	void Dict::start_listen(
		std::string user_father,
		std::string user,
		long long int listen_id
	) {
		//初始化校验
		init_check();
		//参数合法性校验
		check_string_valid__(OPT::start_listen, user_father);
		check_string_valid__(OPT::start_listen, user);
		if (listen_id < 0) {
			throw_dict_error(user_father, user, OPT::start_listen, {},
				error_.invalid_operation_error,
				"The listen id is invalid.");
		}

		UserCheckResult ucr = check_global_users_value__(OPT::start_listen, user_father, user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//操作锁
		if (!ucr.found_su and DICT_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::start_listen, {},
				error_.invalid_operation_error, "Dict has been locked operation.");
		}
		//冻结锁
		if (!ucr.found_su and DICT_FROZEN_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::start_listen, {},
				error_.invalid_operation_error, "You do not have permission to add listen. Dict has been frozen.");
		}
		//su线程ID校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		if (//仅找到su，无需校验权限
			ucr.found_su
			//su ,hu 需要hu有rw权限
			or ((ucr.found_su_and_hu) and (ucr.hu_global_permission == Permission::rw))
			//hu,vu 需要hu有rw权限，vu有r_权限 （监听时vu有r_权限时可以读写监听，是一种特权）
			or (ucr.found_hu_and_vu and ((ucr.hu_global_permission == Permission::rw)and(ucr.vu_global_permission == Permission::r_)))
			) {

			//智能锁
			std::unique_lock lock_0(listeners_.smtx);
			std::unique_lock lock_1(global_listeners_.smtx);

			auto listen_bag_iter = listeners_.listen_map_.find(listen_id);
			if (listen_bag_iter == listeners_.listen_map_.end()) {
				throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
					error_.invalid_operation_error,
					"The listen id does not exist.");
			}
			else {
				auto listen_bag = listen_bag_iter->second;
				if (listen_bag.listen_type == ListenType::global) {
					//进入OPT分区
					auto global_listen_bag_iter = global_listeners_.global_listen_map_.find(listen_bag.OPT_ID);
					if (global_listen_bag_iter == global_listeners_.global_listen_map_.end()) {
						throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
							error_.invalid_operation_error,
							"The listen operation type does not exist.");
					}
					//进入被监听用户分区
					auto listened_iter = global_listen_bag_iter->second.find(listen_bag.listened_user_father_and_user);
					if (listened_iter == global_listen_bag_iter->second.end()) {
						throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
							error_.invalid_operation_error,
							"The listened user does not exist.");
					}
					//进入监听ID分区
					auto listen_id_iter = listened_iter->second.find(listen_id);
					if (listen_id_iter == listened_iter->second.end()) {
						throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
							error_.invalid_operation_error,
							"The listen id does not exist.");
					}

					//更新 全局监听注册表 内监听器状态
					if (listen_id_iter->second.is_work == true) {
						throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
							error_.invalid_operation_error,
							"The listen has already started.");
					}
					else {
						listen_id_iter->second.is_work = true;
					}
					//更新 全局和字典内监听注册索引表 内监听器状态
					listen_bag_iter->second.is_work = true;

					//时间戳获取
					std::string current_time = get_time_string();

					//禁止触发监听，触发容易导致递归

					//日志记录
					log_op(
						current_time,
						user_father,
						user,
						OPT::start_listen,
						{},
						"Success"
					);
				}
				else if ((listen_bag.listen_type == ListenType::node)
					or (listen_bag.listen_type == ListenType::pass)) {

					//进入节点
					if (auto listen_node_ptr = listen_bag.listen_node_ptr.lock()) {
						//智能锁
						std::shared_lock lock(listen_node_ptr->info.smtx);

						//校验是否重复注册无法实现，std::function的内容无法比较

						//进入OPT分区
						auto event_listen_list = listen_node_ptr->info.event_listen_ml_;
						auto OPT_EL = event_listen_list.find(listen_bag.OPT_ID);
						if (OPT_EL == event_listen_list.end()) {
							throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
								error_.invalid_operation_error,
								"The listen operation type does not exist.");
						}
						//进入被监听用户分区
						auto listened_iter = OPT_EL->second.find(listen_bag.listened_user_father_and_user);
						if (listened_iter == OPT_EL->second.end()) {
							throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
								error_.invalid_operation_error,
								"The listened user does not exist.");
						}
						//进入监听ID分区
						auto listen_id_iter = listened_iter->second.find(listen_id);
						if (listen_id_iter == listened_iter->second.end()) {
							throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
								error_.invalid_operation_error,
								"The listen id does not exist.");
						}

						//更新 节点监听注册表 内监听器状态
						if (listen_id_iter->second.is_work == true) {
							throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
								error_.invalid_operation_error,
								"The listen has already started.");
						}
						else {
							listen_id_iter->second.is_work = true;
						}
						//更新 全局和字典内监听注册索引表 内监听器状态
						listen_bag_iter->second.is_work = true;

						//时间戳获取
						std::string current_time = get_time_string();

						//禁止触发监听，触发容易导致递归

						//日志记录
						log_op(
							current_time,
							user_father,
							user,
							OPT::start_listen,
							{},
							"Success"
						);

					}
					else {
						throw_dict_error(user_father, user, OPT::start_listen, {},
							error_.invalid_operation_error,
							"The listen node does not exist.");
					}
				}
				//防御性编程，一般不应该触发到这里
				else {
					throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
						error_.invalid_operation_error,
						"The listen type is invalid.");
				}
			}
		}
		else {
			throw_dict_error(user_father, user, OPT::start_listen, {"NULL_PATH","NULL_PATH"},
				error_.permission_not_enough,
				"You do not have permission to start listen.");
		}
	};
	//暂停监听
	void Dict::stop_listen(
		std::string user_father,
		std::string user,
		long long int listen_id
	) {
		//初始化校验
		init_check();
		//参数合法性校验
		check_string_valid__(OPT::stop_listen, user_father);
		check_string_valid__(OPT::stop_listen, user);
		if (listen_id < 0) {
			throw_dict_error(user_father, user, OPT::stop_listen, {},
				error_.invalid_operation_error,
				"The listen id is invalid.");
		}

		UserCheckResult ucr = check_global_users_value__(OPT::stop_listen, user_father, user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//su线程ID校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}
		//操作锁
		if (!ucr.found_su and DICT_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::stop_listen, {},
				error_.invalid_operation_error, "Dict has been locked operation.");
		}
		//冻结锁
		if (!ucr.found_su and DICT_FROZEN_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::stop_listen, {},
				error_.invalid_operation_error, "You do not have permission to add listen. Dict has been frozen.");
		}

		if (//仅找到su，无需校验权限
			ucr.found_su
			//su ,hu 需要hu有rw权限
			or ((ucr.found_su_and_hu) and (ucr.hu_global_permission == Permission::rw))
			//hu,vu 需要hu有rw权限，vu有r_权限 （监听时vu有r_权限时可以读写监听，是一种特权）
			or (ucr.found_hu_and_vu and ((ucr.hu_global_permission == Permission::rw) and (ucr.vu_global_permission == Permission::r_)))
			) {

			//智能锁
			std::unique_lock lock_0(listeners_.smtx);
			std::unique_lock lock_1(global_listeners_.smtx);

			auto listen_bag_iter = listeners_.listen_map_.find(listen_id);
			if (listen_bag_iter == listeners_.listen_map_.end()) {
				throw_dict_error(user_father, user, OPT::stop_listen, {},
					error_.invalid_operation_error,
					"The listen id does not exist.");
			}
			else {
				auto listen_bag = listen_bag_iter->second;
				if (listen_bag.listen_type == ListenType::global) {
					//进入OPT分区
					auto global_listen_bag_iter = global_listeners_.global_listen_map_.find(listen_bag.OPT_ID);
					if (global_listen_bag_iter == global_listeners_.global_listen_map_.end()) {
						throw_dict_error(user_father, user, OPT::stop_listen, {},
							error_.invalid_operation_error,
							"The listen operation type does not exist.");
					}
					//进入被监听用户分区
					auto listened_iter = global_listen_bag_iter->second.find(listen_bag.listened_user_father_and_user);
					if (listened_iter == global_listen_bag_iter->second.end()) {
						throw_dict_error(user_father, user, OPT::stop_listen, {},
							error_.invalid_operation_error,
							"The listened user does not exist.");
					}
					//进入监听ID分区
					auto listen_id_iter = listened_iter->second.find(listen_id);
					if (listen_id_iter == listened_iter->second.end()) {
						throw_dict_error(user_father, user, OPT::stop_listen, {},
							error_.invalid_operation_error,
							"The listen id does not exist.");
					}

					//更新 全局监听注册表 内监听器状态
					if (listen_id_iter->second.is_work == false) {
						throw_dict_error(user_father, user, OPT::stop_listen, {},
							error_.invalid_operation_error,
							"The listen has already stopped.");
					}
					else {
						listen_id_iter->second.is_work = false;
					}
					//更新 全局和字典内监听注册索引表 内监听器状态
					listen_bag_iter->second.is_work = false;

					//时间戳获取
					std::string current_time = get_time_string();

					//禁止触发监听，触发容易导致递归

					//日志记录
					log_op(
						current_time,
						user_father,
						user,
						OPT::stop_listen,
						{},
						"Success"
					);
				}

				else if ((listen_bag.listen_type == ListenType::node)
					or (listen_bag.listen_type == ListenType::pass)) {

					//进入节点
					if (auto listen_node_ptr = listen_bag.listen_node_ptr.lock()) {
						//智能锁
						std::shared_lock lock(listen_node_ptr->info.smtx);

						//校验是否重复注册无法实现，std::function的内容无法比较

						//进入OPT分区
						auto event_listen_list = listen_node_ptr->info.event_listen_ml_;
						auto OPT_EL = event_listen_list.find(listen_bag.OPT_ID);
						if (OPT_EL == event_listen_list.end()) {
							throw_dict_error(user_father, user, OPT::stop_listen, {},
								error_.invalid_operation_error,
								"The listen operation type does not exist.");
						}
						//进入被监听用户分区
						auto listened_iter = OPT_EL->second.find(listen_bag.listened_user_father_and_user);
						if (listened_iter == OPT_EL->second.end()) {
							throw_dict_error(user_father, user, OPT::stop_listen, {},
								error_.invalid_operation_error,
								"The listened user does not exist.");
						}
						//进入监听ID分区
						auto listen_id_iter = listened_iter->second.find(listen_id);
						if (listen_id_iter == listened_iter->second.end()) {
							throw_dict_error(user_father, user, OPT::stop_listen, {},
								error_.invalid_operation_error,
								"The listen id does not exist.");
						}

						//更新 节点监听注册表 内监听器状态
						if (listen_id_iter->second.is_work == false) {
							throw_dict_error(user_father, user, OPT::stop_listen, {},
								error_.invalid_operation_error,
								"The listen has already stopped.");
						}
						else {
							listen_id_iter->second.is_work = false;
						}
						//更新 全局和字典内监听注册索引表 内监听器状态
						listen_bag_iter->second.is_work = false;

						//时间戳获取
						std::string current_time = get_time_string();

						//禁止触发监听，触发容易导致递归

						//日志记录
						log_op(
							current_time,
							user_father,
							user,
							OPT::stop_listen,
							{},
							"Success"
						);
					}
					else {
						throw_dict_error(user_father, user, OPT::stop_listen, {},
							error_.invalid_operation_error,
							"The listen node does not exist.");
					}
				}
				//防御性编程，一般不应该触发到这里
				else {
					throw_dict_error(user_father, user, OPT::stop_listen, {},
						error_.invalid_operation_error,
						"The listen type is invalid.");
				}
			}
		}
		else {
			throw_dict_error(user_father, user, OPT::stop_listen, {},
				error_.permission_not_enough,
				"You do not have permission to stop listen.");
		}
	};
	//删除监听
	void Dict::del_listen(
		std::string user_father,
		std::string user,
		long long int listen_id
	) {
		//初始化校验
		init_check();
		//参数合法性校验
		check_string_valid__(OPT::del_listen, user_father);
		check_string_valid__(OPT::del_listen, user);
		if (listen_id < 0) {
			throw_dict_error(user_father, user, OPT::del_listen, {},
				error_.invalid_operation_error,
				"The listen id is invalid.");
		}

		UserCheckResult ucr = check_global_users_value__(OPT::add_listen, user_father, user);

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//su线程ID校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}
		//操作锁
		if (!ucr.found_su and DICT_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, OPT::add_listen, {},
				error_.invalid_operation_error, "Dict has been locked operation.");
		}

		if (//仅找到su，无需校验权限
			ucr.found_su
			//su ,hu 需要hu有rw权限
			or ((ucr.found_su_and_hu) and (ucr.hu_global_permission == Permission::rw))
			//hu,vu 需要hu有rw权限，vu有r_权限 （监听时vu有r_权限时可以读写监听，是一种特权）
			or (ucr.found_hu_and_vu and ((ucr.hu_global_permission == Permission::rw) and (ucr.vu_global_permission == Permission::r_)))
			) {

			//智能锁
			std::unique_lock lock_0(listeners_.smtx);
			std::unique_lock lock_1(global_listeners_.smtx);

			auto listen_bag_iter = listeners_.listen_map_.find(listen_id);
			if (listen_bag_iter == listeners_.listen_map_.end()) {
				throw_dict_error(user_father, user, OPT::del_listen, {},
					error_.invalid_operation_error,
					"The listen id does not exist.");
			}
			else {
				auto listen_bag = listen_bag_iter->second;
				if (listen_bag.listen_type == ListenType::global) {
					//进入OPT分区
					auto global_listen_bag_iter = global_listeners_.global_listen_map_.find(listen_bag.OPT_ID);
					if (global_listen_bag_iter == global_listeners_.global_listen_map_.end()) {
						throw_dict_error(user_father, user, OPT::del_listen, {},
							error_.invalid_operation_error,
							"The listen operation type does not exist.");
					}
					//进入被监听用户分区
					auto listened_iter = global_listen_bag_iter->second.find(listen_bag.listened_user_father_and_user);
					if (listened_iter == global_listen_bag_iter->second.end()) {
						throw_dict_error(user_father, user, OPT::del_listen, {},
							error_.invalid_operation_error,
							"The listened user does not exist.");
					}
					//进入监听ID分区
					auto listen_id_iter = listened_iter->second.find(listen_id);
					if (listen_id_iter == listened_iter->second.end()) {
						throw_dict_error(user_father, user, OPT::del_listen, {},
							error_.invalid_operation_error,
							"The listen id does not exist.");
					}

					//删除 全局监听注册表 内监听器
					listened_iter->second.erase(listen_id_iter);

					//时间戳获取
					std::string current_time = get_time_string();

					//禁止触发监听，触发容易导致递归

					//日志记录
					log_op(
						current_time,
						user_father,
						user,
						OPT::del_listen,
						{},
						"Success del a globel listen."
					);
				}
				else if ((listen_bag.listen_type == ListenType::node)
					or (listen_bag.listen_type == ListenType::pass)) {

					//进入节点
					if (auto listen_node_ptr = listen_bag.listen_node_ptr.lock()) {
						//智能锁
						std::shared_lock lock(listen_node_ptr->info.smtx);

						//校验是否重复注册无法实现，std::function的内容无法比较

						//进入OPT分区
						auto event_listen_list = listen_node_ptr->info.event_listen_ml_;
						auto OPT_EL = event_listen_list.find(listen_bag.OPT_ID);
						if (OPT_EL == event_listen_list.end()) {
							throw_dict_error(user_father, user, OPT::del_listen, {},
								error_.invalid_operation_error,
								"The listen operation type does not exist.");
						}
						//进入被监听用户分区
						auto listened_iter = OPT_EL->second.find(listen_bag.listened_user_father_and_user);
						if (listened_iter == OPT_EL->second.end()) {
							throw_dict_error(user_father, user, OPT::del_listen, {},
								error_.invalid_operation_error,
								"The listened user does not exist.");
						}
						//进入监听ID分区
						auto listen_id_iter = listened_iter->second.find(listen_id);
						if (listen_id_iter == listened_iter->second.end()) {
							throw_dict_error(user_father, user, OPT::del_listen, {},
								error_.invalid_operation_error,
								"The listen id does not exist.");
						}

						//删除 节点监听注册表 内监听器
						listened_iter->second.erase(listen_id_iter);

						//时间戳获取
						std::string current_time = get_time_string();

						//禁止触发监听，触发容易导致递归

						//日志记录
						log_op(
							current_time,
							user_father,
							user,
							OPT::del_listen,
							{},
							"Success del a node listen."
						);
					}
					else {
						throw_dict_error(user_father, user, OPT::del_listen, {},
							error_.invalid_operation_error,
							"The listen node does not exist.");
					}
				}
				//防御性编程，一般不应该触发到这里
				else {
					throw_dict_error(user_father, user, OPT::del_listen, {},
						error_.invalid_operation_error,
						"The listen type is invalid.");
				}
			}
		}
		else {
			throw_dict_error(user_father, user, OPT::del_listen, {},
				error_.permission_not_enough,
				"You do not have permission to del listen.");
		}
	};
	//列举监听
	std::vector<Dict::listen_info_bag_check_result> Dict::search_listen(            //！！！暂未实现！！！
		std::string user_father,              //操作者父用户
		std::string user,                     //操作者
		std::string target_listen_user_father,//监听器创建者的父用户
		std::string target_listen_user,       //监听器创建者
		std::string is_listened_user_father,  //被监听者的父用户
		std::string is_listened_user,         //被监听者
		std::vector<std::string> listen_path, //监听路径
		ListUserType list_user_type,
		ListenType listen_type,
		OPT listen_operation_type
	){
		throw_dict_error(user_father, user, OPT::search, {},
			error_.invalid_operation_error, "Not supported function.");
	};

	//=====简便方法=====
	//把"a/b/c"式的路径转换成vector<string>，简便写死路径时使用
	std::vector<std::string> Dict::ptv(std::string path_str) {
		//初始化校验
		init_check();
		if(path_str.empty()){
			throw_dict_error("", "", OPT::ptv, {}, error_.invalid_operation_error, "The path is empty.");
		}
		else {
			std::vector<std::string> keys = split(path_str, '/');
			for (auto& key : keys) {
				check_string_valid__(OPT::ptv, key);
			}
			return keys;
		}
	};

	//=====持久化=====
	////将dict保存到二进制文件中
	void Dict::dict_to_bit(std::string su,
		std::vector<std::string> path,
		std::string file_path,
		bool del_user_info
	) {
		throw_dict_error(std::string(""), std::string(""), OPT::dict_to_bit, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	void Dict::bit_to_dict(std::string su,
		std::vector<std::string> path,
		std::string file_path,
		bool del_user_info
	) {
		throw_dict_error(std::string(""), std::string(""), OPT::bit_to_dict, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	////将dict保存到json文件中
	void Dict::dict_to_json(std::string su,
		std::vector<std::string> path,
		std::string file_path,
		bool del_user_info
	) {
		throw_dict_error(std::string(""), std::string(""), OPT::dict_to_json, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	void Dict::json_to_dict(std::string su,
		std::vector<std::string> path,
		std::string file_path,
		bool del_user_info
	) {
		throw_dict_error(std::string(""), std::string(""), OPT::json_to_dict, {},
			error_.invalid_operation_error, "Not supported function.");
	};
	//原子性跨路径操作根本接口（类事务支持功能，保证原子性和一致性，在被拦截时回滚，内部保证一致性，在真正操作数据前就确保所有操作能完成，无需手动回滚）
	Dict::OperationSearch Dict::atomic_operation(
		std::string user_father,
		std::string user,
		bool rollback_if_intercept,
		const std::vector<operation_info>& operation_list
	) {
		throw_dict_error(user_father, user, OPT::atomic_operation, {},
			error_.invalid_operation_error, "Not supported function.");
	};

	//操作计数
	void Dict::turn_on_operation_counter(std::string su) {
		//初始化校验
		init_check();

		//操作类型设置
		OPT opt = OPT::turn_on_operation_counter;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//su线程校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}
		else {
			throw_dict_error(su, su, opt, {}, error_.permission_not_enough, "You do not have permission to turn on operation counter.");
		}

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//操作计数器开启
		if (is_operation_counter_on_.load(std::memory_order_relaxed)) {
			throw_dict_error(su, su, opt, {}, error_.invalid_operation_error, "The operation counter is already on.");
		}
		else {
			is_operation_counter_on_.store(true, std::memory_order_relaxed);
		}
		
		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			{},
			"Success"
		);
	};
	void Dict::turn_off_operation_counter(std::string su) {
		//初始化校验
		init_check();

		//操作类型设置
		OPT opt = OPT::turn_off_operation_counter;

		//参数合法性校验
		check_string_valid__(opt, su);

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//su线程校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}
		else {
			throw_dict_error(su, su, opt, {}, error_.permission_not_enough, "You do not have permission to turn off operation counter.");
		}

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

		//操作计数器开启
		if (is_operation_counter_on_.load(std::memory_order_relaxed)) {
			is_operation_counter_on_.store(false, std::memory_order_relaxed);
			
		}
		else {
			throw_dict_error(su, su, opt, {}, error_.invalid_operation_error, "The operation counter is already on.");
		}

		//日志记录
		log_op(
			current_time,
			su,
			su,
			opt,
			{},
			"Success"
		);
	};
	long long int Dict::get_operation_counter(
		std::string su, 
		get_oc_type oct, 
		std::vector<std::string> path
	) {
		//初始化校验
		init_check();

		//操作类型设置
		OPT opt = OPT::get_operation_counter;

		//参数合法性校验
		check_string_valid__(opt, su);
		for (auto& key : path) {
			check_string_valid__(opt, key);
		}

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, su, su);

		//su线程校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}
		else {
			throw_dict_error(su, su, opt, {}, error_.permission_not_enough, "You do not have permission to get operation counter.");
		}

		//数据读取
		if (oct == get_oc_type::globel) {
			//操作计数
			operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

			//日志记录
			log_op(
				current_time,
				su,
				su,
				opt,
				{},
				"Success"
			);

			return global_operation_counter_.load(std::memory_order_relaxed);
		}
		else if (oct == get_oc_type::node) {
			//读写操作
			{
				LockedNode locked_node = get_node__(
					opt,
					su,
					su,
					Permission::rw,//或r_
					path,
					NodeType::any,//或dict或value
					LockType::Read,//或Write
					current_time
				);

				//操作计数
				operation_counter oc = operation_counter(this, oc_type::node_operation_counter, &locked_node.node->node_op_counter_);

				//日志记录
				log_op(
					current_time,
					su,
					su,
					opt,
					{},
					"Success"
				);

				return locked_node.node->node_op_counter_.load(std::memory_order_relaxed);
			}
		}
		else if (oct == get_oc_type::all) {
			//操作计数
			operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);

			//日志记录
			log_op(
				current_time,
				su,
				su,
				opt,
				{},
				"Success"
			);

			return all_operation_counter_.load(std::memory_order_relaxed);
		}
		else {
			throw_dict_error(su, su, opt, {}, error_.invalid_operation_error, "The operation counter type is invalid.");
		}
	};

	//==========私有方法定义==========
	//=====数据=================================================
	Dict::Node::Node()
		: is_intercepted(false),
		is_broken(false),
		is_locked(false),
		node_op_counter_(0) {
		// 初始化 node_info 结构
		info.current_lock_type.store(LockType::Unlocked);
		info.lock_count.store(0);
		info.is_dict = false;
		info.node_id = 0;
		// 时间戳初始化为空
		info.create_time = "";
		info.update_time = "";
		info.del_time = "";
		// 键值初始化为空
		info.key = "";
		// 注意：std::any 默认构造即为空，不需要显式初始化
	}

	// Node 析构函数
	Dict::Node::~Node() {
		// 检查节点是否仍处于锁定状态（调试用）
		if (info.lock_count.load() > 0) {
			// 这里可以记录错误日志，但不应抛出异常
			// 因为析构函数中抛出异常会导致未定义行为
		}

		// 清空子节点映射（智能指针会自动释放内存）
		info.children.clear();
		info.del_children.clear();

		// 清空权限表和监听器映射
		info.users_permission.clear();
		for (auto& opt_map : info.event_listen_ml_) {
			for (auto& user_map : opt_map.second) {
				user_map.second.clear();
			}
		}
		info.event_listen_ml_.clear();
	}

	//=====数据=================================================

	//=====操作计数=============================================

	// 操作计数器实现
	Dict::operation_counter::operation_counter(
		Dict* dict,
		oc_type oct,
		std::atomic<long long int>* node_oc_ptr
	) :
		dict_(dict),
		oc_type_(oct),
		node_oc_ptr_(node_oc_ptr)
	{
		if (!dict_->is_operation_counter_on_) return;

		if (oct == oc_type::node_operation_counter || oct == oc_type::all_operation_counter) {
			if (node_oc_ptr_) {
				node_oc_ptr_->fetch_add(1, std::memory_order_relaxed);
			}
		}
		if (oct == oc_type::global_operation_counter || oct == oc_type::all_operation_counter) {
			dict_->global_operation_counter_.fetch_add(1, std::memory_order_relaxed);
		}
		dict_->all_operation_counter_.fetch_add(1, std::memory_order_relaxed);
	}

	Dict::operation_counter::~operation_counter() {
		if (!dict_->is_operation_counter_on_) return;

		if (oc_type_ == oc_type::node_operation_counter || oc_type_ == oc_type::all_operation_counter) {
			if (node_oc_ptr_) {
				node_oc_ptr_->fetch_sub(1, std::memory_order_relaxed);
			}
		}
		if (oc_type_ == oc_type::global_operation_counter || oc_type_ == oc_type::all_operation_counter) {
			dict_->global_operation_counter_.fetch_sub(1, std::memory_order_relaxed);
		}
		dict_->all_operation_counter_.fetch_sub(1, std::memory_order_relaxed);
	}

	//=====操作计数=============================================
	
	//=====时间=================================================

	//内部含有的信息均为YYYY/MM/DD/HH/MM/SS/mmm
	/*
	std::string Dict::get_time_string() {
		// 获取当前时间点（毫秒精度）
		auto now = std::chrono::system_clock::now();

		// 分解为秒和毫秒
		auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
		auto ms = now_ms.time_since_epoch() % 1000;

		// 使用编译期常量格式字符串
		std::ostringstream oss;
		oss << std::format("{:%Y/%m/%d/%H/%M/%S}", now);
		oss << '/' << std::setfill('0') << std::setw(3) << ms.count();

		return oss.str();
	};
	*/
	/*
	std::string Dict::get_time_string() {
		// 获取当前时间点（毫秒精度）
		auto now = std::chrono::system_clock::now();

		// 分离整秒部分和毫秒部分
		auto now_sec = std::chrono::time_point_cast<std::chrono::seconds>(now);
		auto fractional_sec = now - now_sec;

		auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(fractional_sec).count();

		// 使用编译期常量格式字符串
		std::ostringstream oss;
		oss << std::format("{:%Y/%m/%d/%H/%M/%S}", now_sec);  // 输出整数秒
		oss << '/' << std::setfill('0') << std::setw(3) << ms; // 添加毫秒部分

		return oss.str();
	};
	*/
	std::string Dict::get_time_string() {
		auto now = std::chrono::system_clock::now();

		// 获取中国时区（Asia/Shanghai）
		const std::chrono::time_zone* tz = std::chrono::locate_zone("Asia/Shanghai");
		auto local_time = std::chrono::zoned_time(tz, now).get_local_time();

		// 分离秒和毫秒
		auto local_sec = std::chrono::time_point_cast<std::chrono::seconds>(local_time);
		auto fractional_sec = local_time - local_sec;
		auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(fractional_sec).count();

		std::ostringstream oss;
		oss << std::format("{:%Y/%m/%d/%H/%M/%S}", local_sec)
			<< '/' << std::setfill('0') << std::setw(3) << ms;
		return oss.str();
	}

	// 时间权限检查函数
	bool Dict::check_time_permission_valid(const user_info& uinfo, const std::string& current_time) {
		// 如果没有启用时间权限，直接返回有效
		if (!uinfo.using_time_permission) {
			return true;
		}

		// 检查时间区间
		return in_time(uinfo.permission_time_list, current_time);
	}

	// 时间字符串转64位整数（工业级优化）
	uint64_t Dict::time_str_to_uint64(const std::string& s) noexcept {
		// 手动展开的优化计算（比循环快3倍）
		return
			(static_cast<uint64_t>(s[0] - '0') * 10000000000000000ULL) +
			(static_cast<uint64_t>(s[1] - '0') * 1000000000000000ULL) +
			(static_cast<uint64_t>(s[2] - '0') * 100000000000000ULL) +
			(static_cast<uint64_t>(s[3] - '0') * 10000000000000ULL) +
			(static_cast<uint64_t>(s[5] - '0') * 1000000000000ULL) +
			(static_cast<uint64_t>(s[6] - '0') * 100000000000ULL) +
			(static_cast<uint64_t>(s[8] - '0') * 10000000000ULL) +
			(static_cast<uint64_t>(s[9] - '0') * 1000000000ULL) +
			(static_cast<uint64_t>(s[11] - '0') * 100000000ULL) +
			(static_cast<uint64_t>(s[12] - '0') * 10000000ULL) +
			(static_cast<uint64_t>(s[14] - '0') * 1000000ULL) +
			(static_cast<uint64_t>(s[15] - '0') * 100000ULL) +
			(static_cast<uint64_t>(s[17] - '0') * 10000ULL) +
			(static_cast<uint64_t>(s[18] - '0') * 1000ULL) +
			(static_cast<uint64_t>(s[20] - '0') * 100ULL) +
			(static_cast<uint64_t>(s[21] - '0') * 10ULL) +
			(static_cast<uint64_t>(s[22] - '0'));
	}

	// 时间区间判断（工业级严格实现）
	bool Dict::in_time(const std::vector<std::vector<std::string>>& permission_time_list,
		const std::string& current_time) noexcept {
		// 1. 前置检查
		if (permission_time_list.empty() || !check_time_valid(current_time)) {
			return false;
		}

		// 2. 转换当前时间（O(1)）
		const uint64_t current = time_str_to_uint64(current_time);

		// 3. 处理时间区间
		std::vector<std::pair<uint64_t, uint64_t>> intervals;
		intervals.reserve(permission_time_list.size());

		for (const auto& interval : permission_time_list) {
			// 3.1 区间格式校验
			if (interval.size() != 2) return false;

			// 3.2 处理开始时间
			uint64_t start = TIME_MIN;
			if (!interval[0].empty()) {
				if (!check_time_valid(interval[0])) return false;
				start = time_str_to_uint64(interval[0]);
			}

			// 3.3 处理结束时间
			uint64_t end = TIME_MAX;
			if (!interval[1].empty()) {
				if (!check_time_valid(interval[1])) return false;
				end = time_str_to_uint64(interval[1]);
			}

			// 3.4 区间有效性检查
			if (start > end) return false;
			intervals.emplace_back(start, end);
		}

		// 4. 区间连续性检查（O(n)）
		for (size_t i = 1; i < intervals.size(); ++i) {
			// 前一个区间的结束必须 <= 后一个区间的开始
			if (intervals[i - 1].second > intervals[i].first) {
				return false;  // 区间重叠
			}
			// 中间区间不能开放
			if (intervals[i - 1].second == TIME_MAX && i < intervals.size() - 1) {
				return false;  // 中间开放区间
			}
		}

		// 5. 二分查找定位区间（O(log n)）
		size_t low = 0, high = intervals.size();
		while (low < high) {
			size_t mid = low + (high - low) / 2;
			if (current < intervals[mid].first) {
				high = mid;
			}
			else if (current > intervals[mid].second) {
				low = mid + 1;
			}
			else {
				return true;  // 命中区间
			}
		}

		return false;
	}
	
	bool Dict::is_leap_year(int year) noexcept {
		// 处理格里高利历闰年规则（包含世纪年规则）
		return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
	}
	
	// 校验时间字符串是否正确
	bool Dict::check_time_valid(const std::string& time_str) noexcept {
		// 长度必须严格匹配格式 "YYYY/MM/DD/HH/MM/SS/mmm"
		constexpr size_t REQUIRED_LENGTH = 23;
		if (time_str.length() != REQUIRED_LENGTH) {
			return false;
		}

		// 预检查分隔符位置（性能优化）
		if (time_str[4] != '/' || time_str[7] != '/' ||
			time_str[10] != '/' || time_str[13] != '/' ||
			time_str[16] != '/') {
			return false;
		}

		// 提取时间组件（避免字符串拷贝）
		int components[7];
		const char* ptr = time_str.data();

		// 预计算解析位置（固定偏移量）
		constexpr std::array<size_t, 7> offsets = { 0, 5, 8, 11, 14, 17, 20 };
		constexpr std::array<size_t, 7> lengths = { 4, 2, 2, 2, 2, 2, 3 };

		// 并行解析所有组件（优化分支预测）
		for (int i = 0; i < 7; ++i) {
			int value = 0;
			const char* comp_ptr = ptr + offsets[i];

			// 手动转换整数（比sscanf更快）
			for (size_t j = 0; j < lengths[i]; ++j) {
				const char c = comp_ptr[j];
				if (c < '0' || c > '9') return false;
				value = value * 10 + (c - '0');
			}
			components[i] = value;
		}

		// 解包组件
		const int& year = components[0];
		const int& month = components[1];
		const int& day = components[2];
		const int& hour = components[3];
		const int& minute = components[4];
		const int& second = components[5];
		const int& millisecond = components[6];

		// 基础范围校验（分支优化）
		if ((month < 1 || month > 12) ||
			(day < 1 || day > 31) ||
			(hour < 0 || hour > 23) ||
			(minute < 0 || minute > 59) ||
			(second < 0 || second > 59) ||
			(millisecond < 0 || millisecond > 999)) {
			return false;
		}

		// 月份天数校验（查表法）
		static constexpr std::array<int, 13> days_in_month = {
			0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
		};

		// 处理闰年二月
		int max_day = days_in_month[month];
		if (month == 2 && is_leap_year(year)) {
			max_day = 29;
		}

		// 最终日期验证
		return day <= max_day;
	}
	
	// 校验离散时间区间列表参数是否正确
	bool Dict::check_permission_time_list_valid(const std::vector<std::vector<std::string>>& permission_time_list) noexcept {
		// 1. 检查整体结构
		if (permission_time_list.empty()) {
			return true;  // 空区间列表视为有效
		}

		// 2. 检查每个区间
		uint64_t prev_end = 0;  // 上一个区间的结束时间
		bool first_interval = true;

		for (const auto& interval : permission_time_list) {
			// 2.1 检查区间格式
			if (interval.size() != 2) {
				return false;  // 每个区间必须包含两个元素
			}

			const std::string& start_str = interval[0];
			const std::string& end_str = interval[1];

			// 2.2 检查时间格式
			if (!start_str.empty() && !check_time_valid(start_str)) {
				return false;
			}
			if (!end_str.empty() && !check_time_valid(end_str)) {
				return false;
			}

			// 2.3 转换时间值为数值
			uint64_t start_val = start_str.empty() ? TIME_MIN : time_str_to_uint64(start_str);
			uint64_t end_val = end_str.empty() ? TIME_MAX : time_str_to_uint64(end_str);

			// 2.4 检查区间有效性
			if (start_val > end_val) {
				return false;  // 开始时间不能晚于结束时间
			}

			// 2.5 检查区间顺序和非重叠性
			if (!first_interval) {
				if (start_val < prev_end) {
					return false;  // 区间重叠
				}
			}

			prev_end = end_val;
			first_interval = false;
		}

		return true;
	}

	//=====时间=================================================
	
	//=====节点访问=============================================

	// LockedNode 构造函数实现
	Dict::LockedNode::LockedNode(std::shared_ptr<Node> node_ptr, LockType lock_type)
		: node(std::move(node_ptr)), lock_type(lock_type){
		if (!node) return;
		// 先实际加锁
		if (lock_type == LockType::Read) {
			node->info.smtx.lock_shared();
		}
		else if (lock_type == LockType::Write) {
			node->info.smtx.lock();//在这里程序停止
		}
		// 后更新原子状态
		node->info.current_lock_type.store(lock_type, std::memory_order_release);
		node->info.lock_count.fetch_add(1, std::memory_order_acq_rel);
	}

	// LockedNode 析构函数实现
	Dict::LockedNode::~LockedNode() {
		if (!node) return;
		// 先解锁
		if (lock_type == LockType::Read) {
			node->info.smtx.unlock_shared();
		}
		else if (lock_type == LockType::Write) {
			node->info.smtx.unlock();
		}
		// 后更新状态
		const int count = node->info.lock_count.fetch_sub(1, std::memory_order_acq_rel);
		if (count == 1) { // 仅当最后一层锁时重置
			node->info.current_lock_type.store(LockType::Unlocked, std::memory_order_release);
		}
	}

	// 根据路径获取已锁定的节点
	Dict::LockedNode Dict::get_node__(
		OPT operation_type,
		std::string user_father,
		std::string user,
		Permission permission,
		std::vector<std::string> path,
		NodeType end_node_type,
		LockType lock_type,
		std::string& current_time
	) {
		// 1. 校验用户存在性，记录用户类型
		//vu操作时，检验用户是否存在
		UserType user_father_type;
		UserType user_type;
		Permission user_father_global_permission;
		Permission user_global_permission;

		//锁定以读锁锁定UFT
		users_info_tree_.smtx.lock_shared();

		if (user_father != users_info_tree_.UFT.user_name){
			auto it = users_info_tree_.UFT.children_users.find(user_father);
			if (it == users_info_tree_.UFT.children_users.end()) {
				throw_dict_error(user_father, user, operation_type, {}, error_.user_not_found_error, "User father not found: " + user_father);
			}
			else if(it->second.children_users.find(user) == it->second.children_users.end()){
				throw_dict_error(user_father, user, operation_type, {}, error_.user_not_found_error, "User not found: " + user);
			}
			else {
				user_father_type = UserType::hu;
				user_type = UserType::vu;
			}
		}
		else if (user_father == users_info_tree_.UFT.user_name) {
			auto it = users_info_tree_.UFT.children_users.find(user);
			if (user == users_info_tree_.UFT.user_name){
				user_father_type = UserType::su;
				user_type = UserType::su;
			}
			else if (it == users_info_tree_.UFT.children_users.end()) {
				throw_dict_error(user_father, user, operation_type, {}, error_.user_not_found_error, "User not found: " + user);
			}
			else {
				user_father_type = UserType::su;
				user_type = UserType::hu;
			}
		}

		// 校验全局权限
		// 权限参数错误
		//// vu请求rw操作
		if ((user_type == UserType::vu) and (permission == Permission::rw)) {
			throw_dict_error(user_father, user, operation_type, {}, error_.permission_not_enough, 
				"A visitor user attempted to request the 'rw' operation, That is not allowed");
		}
		//// hu, hu / vu, vu 参数到不了这里，在检验用户存在性时就报错出去了

		//su, su时，无需校验
		//su, hu
		if ((user_father_type == UserType::su)and(user_type == UserType::hu)) {
			auto it = users_info_tree_.UFT.children_users.find(user);
			if (it->second.permission < permission) {
				throw_dict_error(user_father, user, operation_type, {}, error_.permission_not_enough, 
					"User father permission not enough");
			}
			else {
				user_father_global_permission = users_info_tree_.UFT.permission;
				user_global_permission = it->second.permission;
			}
		}
		//hu, vu
		if (user_father_type == UserType::hu) {
			auto it = users_info_tree_.UFT.children_users.find(user_father);
			if (it->second.permission < permission) {
				throw_dict_error(user_father, user, operation_type, {}, error_.permission_not_enough, 
					"User father permission not enough");
			}
			else {
				auto it1 = it->second.children_users.find(user);
				if (it1->second.permission < permission) {
					throw_dict_error(user_father, user, operation_type, {}, error_.permission_not_enough, 
						"User permission not enough");
				}
				else {
					user_father_global_permission = it->second.permission;
					user_global_permission = it1->second.permission;
				}
			}
		}

		//用户信息使用完毕，解锁
		users_info_tree_.smtx.unlock_shared();

		// 空路径处理：锁定根节点
		if (path.empty()) {
			// 校验终点与期望是否相符
			if (end_node_type == NodeType::value) {
				throw_dict_error(user_father, user, operation_type, path, error_.invalid_end_node_type_error, 
					"The end node type does not match expectations");
			}
			// 校验根节点权限
			if (user_type != UserType::su) {
				auto it = root_node_->info.users_permission.find(user_father + " " + user);
				if (it == root_node_->info.users_permission.end()) {
					throw_dict_error(user_father, user, operation_type, path, error_.permission_not_enough,
						"Root node permission not enough");
				}
				else {
					const user_info& uinfo = it->second;

					// 检查时间权限有效性
					bool time_permission_valid = check_time_permission_valid(uinfo, current_time);

					// 如果时间权限无效，视为无权限
					Permission effective_permission = time_permission_valid ?
						uinfo.permission : Permission::__;

					if (effective_permission < permission) {
						throw_dict_error(user_father, user, operation_type, path, error_.permission_not_enough,
							"Root node permission not enough");
					}
				}
			}

			if (lock_type == LockType::Unlocked) {
				throw_dict_error(user_father, user, operation_type, path, error_.invalid_operation_type_error,
					"Invalid lock type when operating");
			}

			// 锁定根节点

			// 创建LockedNode对象（自动管理解锁）
			LockedNode locked_node(root_node_, lock_type);
			
			// 检查锁定状态（直接抛出异常，LockedNode会自动解锁）
			if (root_node_->is_locked) {
				throw_dict_error(user_father, user, operation_type, path, error_.invalid_operation_type_error,
					"Root node is locked");
			}

			// 检查弃用状态
			if (root_node_->is_broken.load(std::memory_order_acquire)) {
				throw_dict_error(user_father, user, operation_type, path, error_.path_abandoned_error,
					"Root node abandoned after locking");
			}
			// 校验拦截状态
			if (user_type != UserType::su) {
				if (root_node_->is_intercepted.load(std::memory_order_acquire)) {
					throw_dict_error(user_father, user, operation_type, path, error_.operation_intercepted_error,
						"Root node is intercepted");
				}
			}

			return locked_node;
		}
		// 路径非空
		else {
			//回调调取字段生成
			std::string callback_users = user_father + " " + user;

			std::shared_ptr<Node> current = root_node_;
			current->info.smtx.lock_shared();

			// 使用局部锁管理根节点
			std::shared_lock<std::shared_mutex> root_lock;
			if (!path.empty()) {
				root_lock = std::shared_lock<std::shared_mutex>(current->info.smtx);
			}

			std::shared_ptr<Node> father_node = nullptr;

			// ===== 修正权限状态初始化 =====
			Permission current_min_permission = Permission::__; // 初始为无权限
			bool propagation_stopped = false;
			bool has_explicit_no_permission = false;
			bool skip_further_permission_checks = false;
			bool has_any_permission_record = false;             //是否遇到权限记录
			// 遍历路径
			for (size_t i = 0; i < path.size(); ++i) {
				const std::string& part = path[i];
				const bool is_last = (i == path.size() - 1);

				// 访问当前节点

				// 为当前节点创建局部锁
				std::shared_lock<std::shared_mutex> current_lock(current->info.smtx);

				// 释放前一个父节点锁(安全方式)
				if (i > 0 && father_node) {
					// 不需要显式解锁，局部锁会在作用域结束时自动释放
				}

				// 检查节点弃用状态
				if (current->is_broken.load(std::memory_order_acquire)) {
					throw_dict_error(
						user_father, user, operation_type, 
						std::vector<std::string>(path.begin(), path.begin() + i + 1), 
						error_.path_abandoned_error, "Path abandoned: " + path_to_str__({ path.begin(), path.begin() + i + 1 })
					);
				}

				//检查节点锁定状态
				if ((current->is_locked) and (user_type != UserType::su)) {
					throw_dict_error(
						user_father, user, operation_type, 
						std::vector<std::string>(path.begin(), path.begin() + i + 1), 
						error_.permission_not_enough, "A not super user attempted to access a locked node"
					);
				}

				// 校验拦截状态
				if (user_type != UserType::su) {
					if (current->is_intercepted.load(std::memory_order_acquire)) {
						throw_dict_error(
							user_father, user, operation_type, 
							std::vector<std::string>(path.begin(), path.begin() + i + 1), 
							error_.operation_intercepted_error, 
							"Node is intercepted at: " + path_to_str__({ path.begin(), path.begin() + i + 1 })
						);
					}
				}

				// 路径有效性检查
				if (!is_last and !current->info.is_dict) {
					throw_dict_error(
						user_father, user, operation_type, 
						std::vector<std::string>(path.begin(), path.begin() + i + 1), 
						error_.invalid_path_error, 
						"Non-dict node in path: " + path_to_str__({ path.begin(), path.begin() + i + 1 })
					);
				}

				// ===== 权限动态计算 =====
				if (user_type != UserType::su and !skip_further_permission_checks) {
					// 检查当前节点权限记录
					auto perm_it = current->info.users_permission.find(user_father + " " + user);
					if (perm_it != current->info.users_permission.end()) {
						has_any_permission_record = true; // 标记遇到权限记录
						user_info record = perm_it->second; // 复制防止篡改

						// 时间权限检查
						if (record.using_time_permission and
							!check_time_permission_valid(record, current_time)) {
							record.permission = Permission::__;
						}

						// 更新权限状态
						if (record.permission == Permission::__) {
							has_explicit_no_permission = true;
						}
						else {
							// 仅当不是__时才更新最小权限
							if (current_min_permission == Permission::__ ||
								record.permission < current_min_permission) {
								current_min_permission = record.permission;
							}
						}

						// 检查传播停止 
						if (!record.per_is_recursive and !is_last) {
							propagation_stopped = true;
							skip_further_permission_checks = true;
						}
					}

					// ===== 提前退出检查 =====
					// 规则4：显式无权限立即退出
					if (has_explicit_no_permission) {
						throw_dict_error(
							user_father, user, operation_type,
							std::vector<std::string>(path.begin(), path.begin() + i + 1),
							error_.permission_not_enough,
							"Explicit no permission at: " + path_to_str__({ path.begin(), path.begin() + i + 1 })
						);
					}

					// 规则2：非终点前权限传播停止立即退出（无论权限是否足够）
					if (propagation_stopped) {
						throw_dict_error(
							user_father, user, operation_type,
							std::vector<std::string>(path.begin(), path.begin() + i + 1),
							error_.permission_not_enough,
							"Propagation stopped at: " +
							path_to_str__({ path.begin(), path.begin() + i + 1 })
						);
					}
				}

				// ===== 经过型回调触发 =====
				auto events = current->info.event_listen_ml_.find(static_cast<int>(operation_type));
				//进入OPT分区
				if (events != current->info.event_listen_ml_.end()) {
					//进入被监听者分区
					auto it = events->second.find(callback_users);
					if (it != events->second.end()) {
						//遍历待触发监听
						auto callbacks = it->second;
						for (auto event_callback = callbacks.begin(); event_callback != callbacks.end(); ++event_callback) {
							//确保是经过型回调触发才触发
							if (event_callback->second.is_work and (event_callback->second.listen_type == ListenType::pass)) {
								//判断时间权限
								if (in_time(event_callback->second.permission_time_list, current_time)) {
									//触发回调
									operation_info_bag op_info_bag;
									op_info_bag.user_father    = user_father;
									op_info_bag.user           = user;
									op_info_bag.operation_type = operation_type;
									op_info_bag.is_pass_listen = true;
									op_info_bag.path           = path;
									op_info_bag.begining_path  = path[0];
									op_info_bag.ending_path    = path.back();
									try {
										event_callback->second.callback(op_info_bag, 0, event_callback->second.listen_data_vec);
										//删除一次性监听
										if (event_callback->second.is_disposable) {
											callbacks.erase(event_callback);
										}
									}
									catch (...) {//忽略异常
									}
								}
							}
						}
					}
				}

				// 查找子节点
				auto it = current->info.children.find(part);
				if (it == current->info.children.end()) {
					throw_dict_error(
						user_father, user, operation_type,
						std::vector<std::string>(path.begin(), path.begin() + i + 1),
						error_.path_not_found_error, "Path not found: " + path_to_str__({ path.begin(), path.begin() + i + 1 })
					);
				}

				// 移动到子节点
				father_node = current;
				current = it->second;

				// 终点节点锁定处理
				if (is_last) {
					// 提前释放当前节点的共享锁
					current_lock.unlock();  // 关键修复：手动释放共享锁

					// 创建LockedNode对象（构造函数会自动更新锁状态）
					LockedNode locked_node(current, lock_type);

					// 锁定后状态验证（直接抛出异常，LockedNode会自动解锁）
					if (
						   (current->is_broken.load(std::memory_order_acquire))
						   or
					       (
							   (current->is_locked.load(std::memory_order_acquire)
							    and
							   (user_type != UserType::su))
						   )
						   or
						   (
							    (current->is_intercepted.load(std::memory_order_acquire))
								and
								(user_type != UserType::su)
						    )
					){
						throw_dict_error(user_father, user, operation_type, path, 
							error_.path_abandoned_error, "Node abandoned after locking: " + path_to_str__(path)
						);
					}

					// 校验终点与期望是否相符
					if (((current->info.is_dict == true ) and (end_node_type == NodeType::value)) or
						((current->info.is_dict == false) and (end_node_type == NodeType::dict))) {
						throw_dict_error(user_father, user, operation_type, path, 
							error_.invalid_end_node_type_error, "The end node type does not match expectations"
						);
					}

					// 终点节点权限检查（如果之前未跳过）
					if (user_type != UserType::su && !skip_further_permission_checks) {
						auto perm_it = current->info.users_permission.find(user_father + " " + user);
						if (perm_it != current->info.users_permission.end()) {
							has_any_permission_record = true; // 标记遇到权限记录
							user_info record = perm_it->second;

							if (record.using_time_permission &&
								!check_time_permission_valid(record, current_time)) {
								record.permission = Permission::__;
							}

							if (record.permission == Permission::__) {
								has_explicit_no_permission = true;
							}
							else {
								// 更新最小权限
								if (current_min_permission == Permission::__ ||
									record.permission < current_min_permission) {
									current_min_permission = record.permission;
								}
							}
						}
					}

					// ===== 最终权限检查 =====
					// 规则1：整个路径无权限记录则无权限
					if (!has_any_permission_record) {
						current_min_permission = Permission::__;
					}

					// 规则4：显式无权限覆盖
					if (has_explicit_no_permission) {
						current_min_permission = Permission::__;
					}
					if (user_type != UserType::su) {
						if (current_min_permission < permission) {
							throw_dict_error(
								user_father, user, operation_type, path,
								error_.permission_not_enough,
								"Final permission insufficient: " +
								std::to_string(static_cast<int>(current_min_permission)) + " < " +
								std::to_string(static_cast<int>(permission)) +
								(has_any_permission_record ? "" : " (No permission records in path)")
							);
						}
					}
					//返回已上锁节点
					return locked_node;
				}
			}
			// 不应该到达这里
			throw_dict_error(user_father, user, operation_type, path, error_.operation_failed_error, "Unexpected control flow in get_node__");
		}
	}
	
	//节点id安全赋予与计数
	////请在get_node__后调用，确保安全读写
	void Dict::add_node_id__(long long int &node_id) {
		std::shared_lock lock(node_num_.smtx);
		if (node_num_.recycle_id.size() > 0) {
			node_id = node_num_.recycle_id[node_num_.recycle_id.size() - 1];
			node_num_.recycle_id.pop_back();
		}
		else {
			node_num_.node_id_num_++;
			node_id = node_num_.node_id_num_;
		}
	}
	
	//节点安全id回收
	//仅供回收站调用
	void Dict::del_node_id__(long long int& node_id) {
		std::unique_lock lock(node_num_.smtx);
		node_num_.node_id_num_--;
		node_num_.recycle_id.push_back(node_id);
	};

	//=====节点访问=============================================

	//=====su线程安全===========================================

	void  Dict::check_su_thread_id__() {
		//智能锁
		std::shared_lock lock(dict_name_.smtx);
		// 检查su线程id
		if (std::this_thread::get_id() != dict_name_.su_thread_id) {
			throw_dict_error(std::string(""), std::string(""), OPT::any, {}, error_.operation_failed_error, 
				"Super user only can be one thread keep.");
		}
	};

	//=====su线程安全===========================================

	//=====辅助小方法===========================================

	// 校验字符串类型参数合法性
	void Dict::check_string_valid__(OPT operation_type, std::string str) {
		// 检查是否为空
		if (str.empty()) {
			throw_dict_error(std::string(""), std::string(""), operation_type, {}, error_.invalid_operation_error,"User name cannot be empty.");
		}

		// 检查长度
		const size_t max_length = 64;
		if (str.length() > max_length) {
			throw_dict_error(std::string(""), std::string(""), operation_type, {},error_.invalid_operation_error,"User name '" + str + "' exceeds maximum length of " +std::to_string(max_length) + " characters.");
		}

		// 检查每个字符是否合法（只允许字母、数字、下划线）
		for (char c : str) {
			bool is_valid =
				(c >= 'a' && c <= 'z') ||  // 小写字母
				(c >= 'A' && c <= 'Z') ||  // 大写字母
				(c >= '0' && c <= '9') ||  // 数字
				(c == '_');                // 下划线

			if (!is_valid) {
				// 构建可打印的错误字符表示
				std::string char_repr;
				if (std::isprint(static_cast<unsigned char>(c))) {
					char_repr = "'" + std::string(1, c) + "'";
				}
				else {
					char_repr = "ASCII code " + std::to_string(static_cast<int>(c));
				}

				throw_dict_error(std::string(""), std::string(""), operation_type, {}, error_.invalid_operation_error,
					("User name '" + str + "' contains invalid character: " +char_repr + ". Only letters, numbers and underscores are allowed."));
			}
		}

		// 检查保留字段
		const std::vector<std::string> reserved_names = {"NULL",""};
		for (const auto& name : reserved_names) {
			if (str == name) {
				throw_dict_error(std::string(""), std::string(""), operation_type, {}, error_.invalid_operation_error, ("User name '" + str + "' is a reserved system name."));
			}
		}
	};

	//用户参数自动判断
	Dict::UserCheckResult Dict::check_global_users_value__(OPT operation_type, std::string user_father, std::string user) {
		//锁定UFT
		std::shared_lock read_lock(users_info_tree_.smtx);//读锁
		bool found_su        = false;
		bool found_su_and_hu = false;
		bool found_hu_and_vu = false;
		std::string su_name = std::string("");
		std::string hu_name = std::string("");
		std::string vu_name = std::string("");
		Permission su_global_permission = Permission::rw;
		Permission hu_global_permission = Permission::__;
		Permission vu_global_permission = Permission::__;

		auto it = users_info_tree_.UFT.children_users.find(user_father);
		if (user_father == users_info_tree_.UFT.user_name) {
			if (user == users_info_tree_.UFT.user_name) {
				su_name = users_info_tree_.UFT.user_name;
				su_global_permission = users_info_tree_.UFT.permission;
				found_su = true;
			}
			else {
				auto it1 = users_info_tree_.UFT.children_users.find(user);
				if (it1 == users_info_tree_.UFT.children_users.end()) {
					throw_dict_error(user_father, user, operation_type, {}, error_.invalid_operation_error, "User not found in users family tree.while adding user");
				}
				else {
					su_name = users_info_tree_.UFT.user_name;
					hu_name = it1->first;
					su_global_permission = users_info_tree_.UFT.permission;
					hu_global_permission = it1->second.permission;
					found_su_and_hu = true;
				}
			}
		}
		else if (it != users_info_tree_.UFT.children_users.end()) {
			auto it1 = it->second.children_users.find(user);
			if (it1 == it->second.children_users.end()) {
				throw_dict_error(user_father, user, operation_type, {}, error_.invalid_operation_error, "User not found in users family tree.while adding user");
			}
			else {
				su_name = users_info_tree_.UFT.user_name;
				hu_name = it->first;
				vu_name = it1->first;
				su_global_permission = users_info_tree_.UFT.permission;
				hu_global_permission = it->second.permission;
				vu_global_permission = it1->second.permission;
				found_hu_and_vu = true;
			}
		}
		else {
			throw_dict_error(user_father, user, operation_type, {}, error_.invalid_operation_error, "User not found in users family tree.while adding user");
		}
		//解锁UFT

		//返回结果
		UserCheckResult result;
		result.found_su = found_su;
		result.found_su_and_hu = found_su_and_hu;
		result.found_hu_and_vu = found_hu_and_vu;
		result.su_name = su_name;
		result.hu_name = hu_name;
		result.vu_name = vu_name;
		result.su_global_permission = su_global_permission;
		result.hu_global_permission = hu_global_permission;
		result.vu_global_permission = vu_global_permission;
		return result;
	};
	
	//把路径转换成字符串
	std::string Dict::path_to_str__(std::vector<std::string> path) {
		std::string result;
		for (const auto& part : path) {
			check_string_valid__(OPT::any, part);//“DICT::Dict::check_string_valid__”: 调用非静态成员函数需要一个对象
			result += "/" + part;
		}
		return result;
	};

	//字符串分割
	std::vector<std::string> Dict::split(const std::string& str, char delimiter) {
		std::vector<std::string> tokens;
		std::istringstream tokenStream(str);
		std::string token;
		while (std::getline(tokenStream, token, delimiter)) {
			tokens.push_back(token);
		}
		return tokens;
	};

	//=====辅助小方法===========================================

	//=====回收站===============================================

	//=====回收站核心方法=====
	void Dict::join_recycle__(
		std::string user_father,
		std::string user,
		std::vector<std::string> path,
		std::shared_ptr<Node> father_node,
		const std::string& key,
		long long int node_id)
	{
		const int index = active_index_.load();
		std::lock_guard lock(buffers_[index].mtx);

		// 直接添加新项目（不再检查父路径）
		buffers_[index].items.push_back({
			std::move(user_father),
			std::move(user),
			std::move(path),
			father_node,
			key,  // 新增 key
			node_id
			});

		pending_count_++;
	}

	void Dict::run_recycle__() {
		if (auto_clean_recycle_is_running_.exchange(true)) return;

		recycle_thread_ = std::thread([this] 
			{
				while (auto_clean_recycle_is_running_) {
					// 1. 切换到非活动缓冲区
					const int processing_index = 1 - active_index_.load();
					auto& buffer = buffers_[processing_index];

					// 2. 获取待处理项目
					std::vector<RecycleItem> items_to_process;
					{
						std::lock_guard lock(buffer.mtx);
						if (!buffer.items.empty()) {
							items_to_process.swap(buffer.items);
							pending_count_ -= items_to_process.size();
						}
					}

					// 3. 处理回收项目
					if (!items_to_process.empty()) {
						process_recycle_items__(items_to_process);
					}

					// 4. 休眠
					std::this_thread::sleep_for(
						std::chrono::milliseconds(recycle_interval_.load(std::memory_order_acquire)));
				}
			}
		);
	}

	void Dict::process_recycle_items__(const std::vector<RecycleItem>& items) {
		std::vector<long long int> ids_to_recycle;
		ids_to_recycle.reserve(items.size());

		for (const auto& item : items) {
			if (auto father_ptr = item.father_node_ptr.lock()) {
				std::lock_guard lock(father_ptr->info.smtx);
				// 检查节点是否仍存在于 del_children
				if (father_ptr->info.del_children.count(item.key)) {
					father_ptr->info.del_children.erase(item.key);
				}
			}
			ids_to_recycle.push_back(item.node_id);
		}

		// 批量回收ID
		if (!ids_to_recycle.empty()) {
			std::lock_guard lock(node_num_.smtx);
			auto& recycle = node_num_.recycle_id;
			recycle.insert(recycle.end(), ids_to_recycle.begin(), ids_to_recycle.end());
		}
	}

	void Dict::stop_recycle__() {
		if (!auto_clean_recycle_is_running_.exchange(false)) return;

		if (recycle_thread_.joinable()) {
			recycle_thread_.join();
		}

		// 清理所有缓冲区
		for (auto& buffer : buffers_) {
			std::lock_guard lock(buffer.mtx);
			buffer.items.clear();
		}
		pending_count_ = 0;
	}

	//=====回收站用户接口=====
	void Dict::clean_recycle__() {
		// 0. 检查是否启动自动清理，如果启动了则报错退出
		if (auto_clean_recycle_is_running_.load(std::memory_order_acquire)) {
			throw_dict_error(std::string(""), std::string(""), OPT::clean_recycle, {},
				error_.invalid_operation_error,
				"Cannot clean recycle bin while auto clean is running.");
		}

		// 1. 获取当前活动缓冲区的索引
		const int current_active = active_index_.load(std::memory_order_acquire);
		// 计算非活动缓冲区的索引（即要清理的缓冲区）
		const int processing_index = 1 - current_active;
		auto& buffer = buffers_[processing_index];

		std::vector<RecycleItem> items_to_process;
		{
			// 2. 锁定缓冲区并获取所有项目
			std::lock_guard lock(buffer.mtx);
			if (buffer.items.empty()) {
				return; // 没有可清理的项目
			}
			items_to_process.swap(buffer.items);
			pending_count_.fetch_sub(items_to_process.size(), std::memory_order_release);
		}

		// 3. 处理这些项目（删除节点并回收ID）
		process_recycle_items__(items_to_process);

		// 4. 交换活动缓冲区索引，使刚刚清空的缓冲区成为新的活动缓冲区
		active_index_.store(processing_index, std::memory_order_release);
	}

	std::vector<std::vector<std::string>> Dict::get_recycled_items__(
		std::string user_father,
		std::string user)
	{
		std::vector<std::vector<std::string>> result;

		for (int i = 0; i < 2; ++i) {
			std::lock_guard lock(buffers_[i].mtx);
			for (const auto& item : buffers_[i].items) {
				if (item.user_father == user_father && item.user == user) {
					result.push_back(item.path);
				}
			}
		}

		return result;
	}

	//恢复内容功能                                                        ！！！待实现！！！
	//目标路径为空则尝试恢复到原路径，如果有重名则重命名key为"RECYCLE_num_原key"，设置force_override为true则强制覆盖
	void Dict::restore_recycled_item_(
		std::string user_father,
		std::string user,
		std::vector<std::string> recycle_item_path,
		std::vector<std::string> restore_path,
		bool force_override
	)
	{
		// 1. 在回收站中查找项目
		RecycleItem* found_item = nullptr;
		int found_buffer = -1;

		// 在两个缓冲区中搜索
		for (int i = 0; i < 2; ++i) {
			std::lock_guard lock(buffers_[i].mtx);
			for (auto& item : buffers_[i].items) {
				if (item.path == recycle_item_path) {
					found_item = &item;
					found_buffer = i;
					break;
				}
			}
		}

		if (!found_item) {
			throw_dict_error(user_father, user, OPT::restore_recycled_item, recycle_item_path,
				error_.invalid_operation_error, "Item not found in recycle bin."); // 未找到
		}

		// 2. 获取父节点和节点
		auto father_ptr = found_item->father_node_ptr.lock();
		if (!father_ptr) {
			throw_dict_error(user_father, user, OPT::restore_recycled_item, recycle_item_path,
				error_.invalid_operation_error, "Parent node has been released."); // 父节点已释放
		}

		std::unique_lock father_lock(father_ptr->info.smtx);
		auto node_it = father_ptr->info.del_children.find(found_item->key);
		if (node_it == father_ptr->info.del_children.end()) {
			throw_dict_error(user_father, user, OPT::restore_recycled_item, recycle_item_path,
				error_.invalid_operation_error, "Item not found in parent node's del_children."); // 节点不存在); // 节点不存在
		}
		auto node = node_it->second;

		// 3. 确定恢复位置
		std::shared_ptr<Node> target_father;
		std::string target_key;

		if (restore_path.empty()) {
			// 恢复到原位置
			target_father = father_ptr;
			target_key = found_item->key;
		}
		else {
			std::string time_str = get_time_string();
			// 获取新父节点
			LockedNode locked_target = get_node__(
				OPT::restore_recycled_item, 
				user_father, 
				user,
				Permission::rw,
				restore_path,
				NodeType::dict,
				LockType::Write,
				time_str
			);
			target_father = locked_target.node;
			target_key = restore_path.back();
		}

		// 4. 处理目标位置冲突
		std::unique_lock target_lock(target_father->info.smtx);
		if (target_father->info.children.count(target_key)) {
			if (force_override) {
				// 递归删除现有节点
				del(user_father, user, restore_path);
			}
			else {
				// 生成唯一key: RECYCLE_原key
				int counter = 0;
				std::string new_key;
				do {
					new_key = "RECYCLE_" + std::to_string(counter++) + "_" + found_item->key;
				} while (target_father->info.children.count(new_key));

				target_key = new_key;
			}
		}

		// 5. 恢复节点
		target_father->info.children[target_key] = node;
		father_ptr->info.del_children.erase(found_item->key);

		// 6. 从回收站移除
		std::lock_guard lock(buffers_[found_buffer].mtx);
		auto& items = buffers_[found_buffer].items;
		items.erase(std::remove_if(items.begin(), items.end(),
			[&](const RecycleItem& i) {
				return i.path == recycle_item_path;
			}), items.end());
		pending_count_--;
	}
	//=====回收站===============================================

	//=====日志=================================================
	void Dict::run_auto_clean_log__() {
		if (log_is_running_.exchange(true)) return;
		log_thread_ = std::thread([this]
			{
				while (log_is_running_) {
					// 1. 切换到非活动缓冲区
					const int processing_index = 1 - log_active_index_.load();
					auto& buffer = buffers_[processing_index];

					// 2. 清理日志
					buffer.mtx.lock();
					buffer.items.clear();
					buffer.mtx.unlock();

					// 3. 休眠
					std::this_thread::sleep_for(
						std::chrono::milliseconds(recycle_interval_));
				}
			}
		);
	};

	void Dict::stop_auto_clean_log__() {
		if (!log_is_running_.exchange(false)) return;

		if (log_thread_.joinable()) {
			log_thread_.join();
		}

		// 清理所有缓冲区
		for (auto& buffer : log_buffers_) {
			std::lock_guard lock(buffer.mtx);
			buffer.items.clear();
		}
		log_pending_count_ = 0;
	};

	void Dict::add_log_item__(A_LOG log_item) {
		std::string time_str = get_time_string();

		const int index = log_active_index_.load(std::memory_order_acquire);
		std::lock_guard lock(log_buffers_[index].mtx);

		log_buffers_[index].items.push_back(log_item);
		log_pending_count_++;
	};

	void Dict::set_auto_clean_log_time__(int time) {
		log_recycle_interval_.store(time);
	};

	void Dict::clean_log_items__() {
		// 1. 切换到非活动缓冲区
		const int processing_index = 1 - log_active_index_.load();
		auto& buffer = buffers_[processing_index];

		// 2. 清理日志
		buffer.mtx.lock();
		buffer.items.clear();
		buffer.mtx.unlock();
	};
	
	//日志存储功能                                                        ！！！待实现！！！
	void Dict::save_log__(std::string save_path) {
		
	};

	std::vector<Dict::A_LOG> Dict::get_log_items__(
		std::string user_father,
		std::string user
	) {
		// 1. 切换到非活动缓冲区
		const int processing_index = 1 - log_active_index_.load();
		auto& buffer = log_buffers_[processing_index];

		// 2. 获取日志
		std::vector<A_LOG> result = {};
		buffer.mtx.lock();
		for (const auto& item : buffer.items) {
			if (item.user_father == user_father && item.user == user) {
				result.push_back(item);
			}
		}
		buffer.mtx.unlock();

		return result;
	};

	void Dict::print_log_item__(A_LOG log_item) {
		if (print_log_.load(std::memory_order_acquire)) {
			if (log_item.error_type.empty()) {
				std::cout << log_item.log_time
					<< " [T_DICT_DB][OPT_LOG][OP_START_TIME:"
					<< log_item.op_start_time
					<< "][user_father:"
					<< log_item.user_father
					<< "][user:"
					<< log_item.user
					<< "][operation_type:"
					<< static_cast<int>(log_item.operation_type)
					<< "][path:"
					<< log_item.path
					<< "]"
					<< log_item.message
					<< std::endl;
			}
			else {
				std::cout << log_item.error_time
					<< " [T_DICT_DB][ERR_LOG][__ERROR__TIME:"
					<< log_item.error_time
					<< "][user_father:"
					<< log_item.user_father
					<< "][user:"
					<< log_item.user
					<< "][operation_type:"
					<< static_cast<int>(log_item.operation_type)
					<< "][path:"
					<< log_item.path
					<< "][error_type:"
					<< log_item.error_type
					<< "]"
					<< log_item.message
					<< std::endl;
			}
		}
	};

	//=====日志=================================================

	//=====监听=================================================
	
	//请在锁定listeners_后调用，确保安全读写
	long long int Dict::add_listen_id() {
		if (listeners_.recycle_listen_id.size() > 0) {
			long long int listen_id = listeners_.recycle_listen_id.back();
			node_num_.recycle_id.pop_back();
			return listen_id;
		}
		else {
			listeners_.listen_id_num++;
			long long int listen_id = listeners_.listen_id_num;
			return listen_id;
		}
	};

	void Dict::recycle_listen_id(long long int listen_id) {
		listeners_.listen_id_num--;
		listeners_.recycle_listen_id.push_back(listen_id);
	};
	//=====监听=================================================

	//=====拦截=================================================

	long long int Dict::add_intercept_id() {
		if (intercept_info_.recycle_intercept_id.size() > 0) {
			long long int intercept_id = intercept_info_.recycle_intercept_id.back();
			intercept_info_.recycle_intercept_id.pop_back();
			return intercept_id;
		}
		else {
			intercept_info_.intercept_num++;
			long long int intercept_id = intercept_info_.intercept_num;
			return intercept_id;
		}
	};

	void Dict::recycle_intercept_id(long long int intercept_id) {
		intercept_info_.intercept_num--;
		intercept_info_.recycle_intercept_id.push_back(intercept_id);
	};

	//=====拦截=================================================

	//=====错误抛出=============================================
	[[noreturn]] void Dict::throw_dict_error(
		std::string user_father,
		std::string user,
		OPT operation_type,
		std::vector<std::string> path,
		std::string error_type,
		std::string message
	) {
		std::string time_str = get_time_string();
		std::string path_str = path_to_str__(path);
		if (turn_on_error_log_.load(std::memory_order_acquire)) {
			A_LOG a_error_log;
			a_error_log.error_time = time_str;
			a_error_log.user_father = user_father;
			a_error_log.user = user;
			a_error_log.operation_type = operation_type;
			a_error_log.path = path_str;
			a_error_log.error_type = error_type;
			a_error_log.message = message;
			add_log_item__(a_error_log);
			if (print_log_.load(std::memory_order_acquire)) {
				print_log_item__(a_error_log);
			}
			std::string full_msg;
			full_msg = time_str + "[T_DICT][ERROR][fu:" + user_father + " cu:" + user + "][operation_type:" + std::to_string(static_cast<int>(operation_type)) + "][" + error_type + "][parh: " + path_str + "]" + message;
			throw std::runtime_error(full_msg);
		}
		else {
			std::string full_msg;
			full_msg = time_str + "[T_DICT][ERROR][fu:" + user_father + " cu:" + user + "][operation_type:" + std::to_string(static_cast<int>(operation_type)) + "][" + error_type + "][parh: " + path_str + "]" + message;
			throw std::runtime_error(full_msg);
		}
	};
	//=====错误抛出=============================================

	//=====方法实现模板=========================================
	void Dict::globel_function_black(
		std::string user_father, 
		std::string user
	) {
		//初始化校验
		init_check();
		
		//操作类型设置
		OPT opt = OPT::any;

		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);

		

		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//su线程校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		//操作计数
		operation_counter oc = operation_counter(this, oc_type::global_operation_counter, nullptr);
		

		//根据需要选择
		globel_allowed_r_(opt, current_time, ucr, user_father, user);
		globel_allowed_rw(opt, current_time, ucr, user_father, user);

		//读写操作

		std::any old_value = 0;
		std::any new_value = 0;

		//触发监听
		globel_trigger_listeners(user_father, user, opt, current_time, old_value, new_value);

		//日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};

	void Dict::node_function_black(
		std::string user_father, 
		std::string user, 
		std::vector<std::string> path
	) {
		//初始化校验
		init_check();

		//操作类型设置
		OPT opt = OPT::any;
		
		//参数合法性校验
		check_string_valid__(opt, user_father);
		check_string_valid__(opt, user);
		for (auto& key : path) {
			check_string_valid__(opt, key);
		}
		
		//获取操作开始时间
		std::string current_time = get_time_string();

		//权限校验
		UserCheckResult ucr = check_global_users_value__(opt, user_father, user);

		//su线程校验
		if (ucr.found_su) {
			check_su_thread_id__();
		}

		//根据需要选择
		globel_allowed_r_(opt, current_time, ucr, user_father, user);
		globel_allowed_rw(opt, current_time, ucr, user_father, user);
		
		//读写操作
		{
			LockedNode locked_node = get_node__(
				opt,
				user_father,
				user,
				Permission::rw,//或r_
				path,
				NodeType::any,//或dict或value
				LockType::Read,//或Write
				current_time
			);

			//操作计数
			operation_counter oc = operation_counter(this, oc_type::node_operation_counter, &locked_node.node->node_op_counter_);
			
			
			//读写操作
			std::string new_key = "";
			std::any old_value = 0;
			std::any new_value = 0;
			std::string searched_key = "";

			//触发监听
			node_trigger_listeners(
				user_father,
				user,
				opt,
				current_time,
				path,
				new_key,
				old_value,
				new_value,
				searched_key,
				locked_node.node
			);
		}
		//日志记录
		log_op(
			current_time,
			user_father,
			user,
			opt,
			{},
			"Success"
		);
	};

	void Dict::init_check() {
		//初始化校验
		if (!is_init_.load(std::memory_order_acquire)) {
			throw_dict_error(std::string(""), std::string(""), OPT::any, {},error_.invalid_operation_error, "Dict not init");
		}
	}

	bool Dict::globel_allowed_rw(
		OPT operation_type,
		std::string current_time,
		UserCheckResult ucr,
		std::string user_father,
		std::string user
	) {
		if (ucr.found_su) {
			return true;
		}
		else if (DICT_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, operation_type, {},
				error_.invalid_operation_error, "You do not have the authority to request read and write permissions. Dict is locked.");
		}
		else if (DICT_FROZEN_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, operation_type, {},
				error_.invalid_operation_error, "You do not have the authority to request read and write permissions. Dict is frozen.");
		}
		else {
			if (ucr.found_su_and_hu and (static_cast<int>(ucr.hu_global_permission) == 2)) {
				return true;
			}
			else if (ucr.found_hu_and_vu) {
				throw_dict_error(user_father, user, operation_type, {},
					error_.invalid_operation_error, "Visit users do not have the authority to request read and write permissions");
			}
			else {
				return false;
			}
		}
	};

	bool Dict::globel_allowed_r_(
		OPT operation_type,
		std::string current_time,
		UserCheckResult ucr,
		std::string user_father,
		std::string user
	) {
		if (ucr.found_su) {
			return true;
		}
		else if (DICT_LOCK.load(std::memory_order_acquire)) {
			throw_dict_error(user_father, user, operation_type, {},
				error_.invalid_operation_error, "You do not have the authority to request read permissions. Dict is locked.");
		}
		else {
			if (ucr.found_su_and_hu and (static_cast<int>(ucr.hu_global_permission) >= 1)) {
				return true;
			}
			else if (ucr.found_hu_and_vu and (static_cast<int>(ucr.hu_global_permission) >= 1) and
				(static_cast<int>(ucr.vu_global_permission) == 1)) {
				return true;
			}
			else {
				throw_dict_error(user_father, user, operation_type, {},
					error_.invalid_operation_error, "You do not have the authority to request read permissions. Dict is locked.");
			}
		}
	};
	
	void Dict::globel_trigger_listeners(
		std::string user_father,
		std::string user,
		OPT operation_type,
		std::string current_time,
		std::any old_value,
		std::any new_value
	) {
		//全局监听触发
		//键合成
		std::string l_key = user_father + " " + user;
		//智能锁
		std::unique_lock lock(global_listeners_.smtx);
		//进入OPT分区
		auto OPT_EL = global_listeners_.global_listen_map_.find(static_cast<int>(operation_type));
		if (OPT_EL != global_listeners_.global_listen_map_.end()) {
			auto USER_EL = OPT_EL->second.find(l_key);
			if (USER_EL != OPT_EL->second.end()) {
				//遍历待触发监听
				auto callbacks = USER_EL->second;
				for (auto event_callback = callbacks.begin(); event_callback != callbacks.end(); ++event_callback) {
					//确保是经过型回调触发才触发
					if (event_callback->second.is_work) {
						//判断时间权限
						if (in_time(event_callback->second.permission_time_list, current_time)) {
							//触发回调
							operation_info_bag op_info_bag;
							op_info_bag.user_father = user_father;
							op_info_bag.user = user;
							op_info_bag.operation_type = operation_type;
							op_info_bag.is_pass_listen = false;
							//op_info_bag.path = {};
							//op_info_bag.begining_path = path[0];
							//op_info_bag.ending_path = path.back();
							//if (path.size() > 2) {
							//	  op_info_bag.between_path_lenth = path.size() - 2;
							//}
							//else {
							//    op_info_bag.between_path_lenth = 0;
							//}
							//op_info_bag.target_path;
							//op_info_bag.new_key;
							op_info_bag.new_value;
							//op_info_bag.search_key;
							try {
								event_callback->second.callback(op_info_bag, 0, event_callback->second.listen_data);
								//删除一次性监听
								if (event_callback->second.is_disposable) {
									callbacks.erase(event_callback);
								}
							}
							catch (...) {//忽略异常
							}
						}
					}
				}
			}
		}
	};

	void Dict::node_trigger_listeners(
		std::string user_father,
		std::string user,
		OPT operation_type,
		std::string current_time,
		std::vector<std::string> path,
		std::string new_key,
		std::any old_value,
		std::any new_value,
		std::string searched_key,
		std::shared_ptr<Node> locked_node
	) {
		//监听触发
		//键合成
		std::string l_key = user_father + " " + user;
		//进入OPT分区
		auto OPT_EL = locked_node->info.event_listen_ml_.find(static_cast<int>(operation_type));
		if (OPT_EL != locked_node->info.event_listen_ml_.end()) {
			auto USER_EL = OPT_EL->second.find(l_key);
			if (USER_EL != OPT_EL->second.end()) {
				//遍历待触发监听
				auto callbacks = USER_EL->second;
				for (auto event_callback = callbacks.begin(); event_callback != callbacks.end(); ++event_callback) {
					//确保是经过型回调触发才触发
					if (event_callback->second.is_work and (event_callback->second.listen_type != ListenType::pass)) {
						//判断时间权限
						if (in_time(event_callback->second.permission_time_list, current_time)) {
							//触发回调
							operation_info_bag op_info_bag;
							op_info_bag.user_father = user_father;
							op_info_bag.user = user;
							op_info_bag.operation_type = operation_type;
							op_info_bag.is_pass_listen = false;
							op_info_bag.path = path;
							op_info_bag.begining_path = path[0];
							op_info_bag.ending_path = path.back();
							if (path.size() > 2) {
								op_info_bag.between_path_lenth = path.size() - 2;
							}
							else {
								op_info_bag.between_path_lenth = 0;
							}
							op_info_bag.target_path; //单路径方法不使用
							op_info_bag.new_key = new_key;
							op_info_bag.new_value = new_value;
							op_info_bag.search_key = searched_key;
							try {
								event_callback->second.callback(op_info_bag, 0, event_callback->second.listen_data_vec);
								//删除一次性监听
								if (event_callback->second.is_disposable) {
									callbacks.erase(event_callback);
								}
							}
							catch (...) {//忽略异常
							}
						}
					}
				}
			}
		}
	};

	void Dict::log_op(
		std::string current_time,
		std::string user_father,
		std::string user,
		OPT operation_type,
		std::vector<std::string> path,
		std::string message
	) {
		if (turn_on_log_.load(std::memory_order_acquire)) {
			std::string log_time = get_time_string();
			A_LOG a_log;
			a_log.log_time = log_time;
			a_log.op_start_time = current_time;
			a_log.user_father = user_father;
			a_log.user = user;
			a_log.operation_type = operation_type;
			a_log.path = path_to_str__(path);
			a_log.message = message;
			add_log_item__(a_log);
			if (print_log_.load(std::memory_order_acquire)) {
				print_log_item__(a_log);
			}
		}
	};
};